Python Classes/Objects - W3Schools

文章推薦指數: 80 %
投票人數:10人

Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. Tutorials References Exercises Videos Menu Login FreeWebsite GetCertified Pro HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP BOOTSTRAP HOWTO W3.CSS C C++ C# REACT R JQUERY DJANGO TYPESCRIPT NODEJS MYSQL    Darkmode Darkcode × Tutorials HTMLandCSS LearnHTML LearnCSS LearnRWD LearnBootstrap LearnW3.CSS LearnColors LearnIcons LearnGraphics LearnSVG LearnCanvas LearnHowTo LearnSass DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery JavaScript LearnJavaScript LearnjQuery LearnReact LearnAngularJS LearnJSON LearnAJAX LearnAppML LearnW3.JS Programming LearnPython LearnJava LearnC LearnC++ LearnC# LearnR LearnKotlin LearnGo LearnDjango LearnTypeScript ServerSide LearnSQL LearnMySQL LearnPHP LearnASP LearnNode.js LearnRaspberryPi LearnGit LearnAWSCloud WebBuilding CreateaWebsiteNEW WhereToStart WebTemplates WebStatistics WebCertificates WebDevelopment CodeEditor TestYourTypingSpeed PlayaCodeGame CyberSecurity Accessibility Blog DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel LearnGoogleSheets XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery × References HTML HTMLTagReference HTMLBrowserSupport HTMLEventReference HTMLColorReference HTMLAttributeReference HTMLCanvasReference HTMLSVGReference GoogleMapsReference CSS CSSReference CSSBrowserSupport CSSSelectorReference Bootstrap3Reference Bootstrap4Reference W3.CSSReference IconReference SassReference JavaScript JavaScriptReference HTMLDOMReference jQueryReference AngularJSReference AppMLReference W3.JSReference Programming PythonReference JavaReference ServerSide SQLReference MySQLReference PHPReference ASPReference XML XMLDOMReference XMLHttpReference XSLTReference XMLSchemaReference CharacterSets HTMLCharacterSets HTMLASCII HTMLANSI HTMLWindows-1252 HTMLISO-8859-1 HTMLSymbols HTMLUTF-8 × ExercisesandQuizzes Exercises HTMLExercises CSSExercises JavaScriptExercises PythonExercises SQLExercises PHPExercises JavaExercises CExercises C++Exercises C#Exercises jQueryExercises React.jsExercises MySQLExercises Bootstrap5Exercises Bootstrap4Exercises Bootstrap3Exercises NumPyExercises PandasExercises SciPyExercises TypeScriptExercises ExcelExercises RExercises GitExercises KotlinExercises GoExercises Quizzes HTMLQuiz CSSQuiz JavaScriptQuiz PythonQuiz SQLQuiz PHPQuiz JavaQuiz CQuiz C++Quiz C#Quiz jQueryQuiz React.jsQuiz MySQLQuiz Bootstrap5Quiz Bootstrap4Quiz Bootstrap3Quiz NumPyQuiz PandasQuiz SciPyQuiz TypeScriptQuiz XMLQuiz RQuiz GitQuiz KotlinQuiz CyberSecurityQuiz AccessibilityQuiz Courses HTMLCourse CSSCourse JavaScriptCourse FrontEndCourse PythonCourse SQLCourse PHPCourse JavaCourse C++Course C#Course jQueryCourse React.jsCourse Bootstrap4Course Bootstrap3Course NumPyCourse PandasCourse TypeScriptCourse XMLCourse RCourse DataAnalyticsCourse CyberSecurityCourse AccessibilityCourse Certificates HTMLCertificate CSSCertificate JavaScriptCertificate FrontEndCertificate PythonCertificate SQLCertificate PHPCertificate JavaCertificate C++Certificate C#Certificate jQueryCertificate React.jsCertificate MySQLCertificate Bootstrap5Certificate Bootstrap4Certificate Bootstrap3Certificate TypeScriptCertificate XMLCertificate ExcelCertificate DataScienceCertificate CyberSecurityCertificate AccessibilityCertificate × Tutorials References Exercises GetCertified Spaces Videos Shop Pro PythonTutorial PythonHOME PythonIntro PythonGetStarted PythonSyntax PythonComments PythonVariables PythonVariables VariableNames AssignMultipleValues OutputVariables GlobalVariables VariableExercises PythonDataTypes PythonNumbers PythonCasting PythonStrings PythonStrings SlicingStrings ModifyStrings ConcatenateStrings FormatStrings EscapeCharacters StringMethods StringExercises PythonBooleans PythonOperators PythonLists PythonLists AccessListItems ChangeListItems AddListItems RemoveListItems LoopLists ListComprehension SortLists CopyLists JoinLists ListMethods ListExercises PythonTuples PythonTuples AccessTuples UpdateTuples UnpackTuples LoopTuples JoinTuples TupleMethods TupleExercises PythonSets PythonSets AccessSetItems AddSetItems RemoveSetItems LoopSets JoinSets SetMethods SetExercises PythonDictionaries PythonDictionaries AccessItems ChangeItems AddItems RemoveItems LoopDictionaries CopyDictionaries NestedDictionaries DictionaryMethods DictionaryExercise PythonIf...Else PythonWhileLoops PythonForLoops PythonFunctions PythonLambda PythonArrays PythonClasses/Objects PythonInheritance PythonIterators PythonScope PythonModules PythonDates PythonMath PythonJSON PythonRegEx PythonPIP PythonTry...Except PythonUserInput PythonStringFormatting FileHandling PythonFileHandling PythonReadFiles PythonWrite/CreateFiles PythonDeleteFiles PythonModules NumPyTutorial PandasTutorial SciPyTutorial DjangoTutorial PythonMatplotlib MatplotlibIntro MatplotlibGetStarted MatplotlibPyplot MatplotlibPlotting MatplotlibMarkers MatplotlibLine MatplotlibLabels MatplotlibGrid MatplotlibSubplot MatplotlibScatter MatplotlibBars MatplotlibHistograms MatplotlibPieCharts MachineLearning GettingStarted MeanMedianMode StandardDeviation Percentile DataDistribution NormalDataDistribution ScatterPlot LinearRegression PolynomialRegression MultipleRegression Scale Train/Test DecisionTree ConfusionMatrix HierarchicalClustering LogisticRegression GridSearch CategoricalData K-means BootstrapAggregation CrossValidation AUC-ROCCurve K-nearestneighbors PythonMySQL MySQLGetStarted MySQLCreateDatabase MySQLCreateTable MySQLInsert MySQLSelect MySQLWhere MySQLOrderBy MySQLDelete MySQLDropTable MySQLUpdate MySQLLimit MySQLJoin PythonMongoDB MongoDBGetStarted MongoDBCreateDatabase MongoDBCreateCollection MongoDBInsert MongoDBFind MongoDBQuery MongoDBSort MongoDBDelete MongoDBDropCollection MongoDBUpdate MongoDBLimit PythonReference PythonOverview PythonBuilt-inFunctions PythonStringMethods PythonListMethods PythonDictionaryMethods PythonTupleMethods PythonSetMethods PythonFileMethods PythonKeywords PythonExceptions PythonGlossary ModuleReference RandomModule RequestsModule StatisticsModule MathModule cMathModule PythonHowTo RemoveListDuplicates ReverseaString AddTwoNumbers PythonExamples PythonExamples PythonCompiler PythonExercises PythonQuiz PythonCertificate PythonClassesandObjects ❮Previous Next❯ PythonClasses/Objects Pythonisanobjectorientedprogramminglanguage. AlmosteverythinginPythonisanobject,withitspropertiesandmethods. AClassislikeanobjectconstructor,ora"blueprint"forcreatingobjects. CreateaClass Tocreateaclass,usethekeywordclass: Example CreateaclassnamedMyClass,withapropertynamedx: classMyClass: x=5 TryitYourself» CreateObject NowwecanusetheclassnamedMyClasstocreateobjects: Example Createanobjectnamedp1,andprintthevalueofx: p1=MyClass()print(p1.x) TryitYourself» The__init__()Function Theexamplesaboveareclassesandobjectsintheirsimplestform,andare notreallyusefulinreallifeapplications. Tounderstandthemeaningofclasseswehavetounderstandthebuilt-in__init__() function. Allclasseshaveafunctioncalled__init__(),whichisalwaysexecutedwhen theclassisbeinginitiated. Usethe__init__()functiontoassignvaluestoobjectproperties,orother operationsthatarenecessarytodowhentheobject isbeingcreated: Example CreateaclassnamedPerson,usethe__init__()functiontoassignvalues fornameandage: classPerson: def__init__(self,name,age):    self.name=name   self.age=agep1=Person("John", 36) print(p1.name)print(p1.age) TryitYourself» Note:The__init__()functioniscalledautomaticallyeverytimetheclassisbeingusedtocreateanewobject. ObjectMethods Objectscanalsocontainmethods.Methodsinobjectsarefunctionsthat belongtotheobject. LetuscreateamethodinthePersonclass: Example Insertafunctionthatprintsagreeting,andexecuteitonthep1object: classPerson: def__init__(self,name,age):    self.name=name   self.age=age defmyfunc(self):    print("Hellomynameis"+self.name)p1=Person("John", 36)p1.myfunc() TryitYourself» Note:Theselfparameter isareferencetothecurrentinstanceoftheclass,andisusedtoaccessvariablesthatbelongtotheclass. TheselfParameter Theselfparameterisareferencetothe currentinstanceoftheclass,andisusedtoaccessvariablesthatbelongstotheclass. Itdoesnothavetobenamedself,youcan callitwhateveryoulike,butithastobethefirstparameterofanyfunction intheclass: Example Usethewordsmysillyobjectandabcinsteadofself: classPerson: def__init__(mysillyobject,name,age):    mysillyobject.name=name   mysillyobject.age=age defmyfunc(abc):    print("Hellomynameis"+abc.name)p1=Person("John", 36)p1.myfunc() TryitYourself» ModifyObjectProperties Youcanmodifypropertiesonobjectslikethis: Example Settheageofp1to40: p1.age=40 TryitYourself» DeleteObjectProperties Youcandeletepropertiesonobjectsbyusingthe delkeyword: Example Deletetheagepropertyfromthep1object: delp1.age TryitYourself» DeleteObjects Youcandeleteobjectsbyusingthedelkeyword: Example Deletethep1object: delp1 TryitYourself» ThepassStatement classdefinitionscannotbeempty,butif youforsomereasonhaveaclassdefinitionwithnocontent,putinthepassstatementtoavoidgettinganerror. Example classPerson: pass TryitYourself» TestYourselfWithExercises Exercise: CreateaclassnamedMyClass: MyClass: x=5 SubmitAnswer» StarttheExercise ❮Previous Next❯ NEW WejustlaunchedW3Schoolsvideos Explorenow COLORPICKER Getcertifiedbycompletingacoursetoday! w3schoolsCERTIFIED.2022 Getstarted CODEGAME PlayGame



請為這篇文章評分?