'''Classes can (and should) have docstrings too, just like modules and functions''' Let's create a class that stores a string and a number: So, in most of the cases, we usually only implement the special method, _init()_. However, it's very rare to actually need to implement _new()_ because Python constructs our objects for us. In Python, objects are created in two steps: Although it's not required, Python classes can have something similar to a constructor: the _init_() method. In particular, C++ programmers may find it odd that Python classes don't have explicit constructors and destructors. There is nothing that a Python class absolutely must have, other than a name. Many classes define methods, but this one does not. Many classes are inherited from other classes, but the one in the example is not. Note that this is working even though there are no instances of the class yet. In this case, the class is basically an objec with field names attached to it. Then, we attached attributes to the class by assigning name to it outside of the class. The pass statement in Python is like an empty set of curly braces in Java or C. It's a statement that does nothing, and it's a good placeholder when we're stubbing out functions or classes. This is a Python reserved word that just means move along, nothing to see here. This Student class doesn't define any methods or attributes, but syntactically, there needs to be something in the definition, thus the pass statement. In the code, the pass is the no-operation statement. The first line not indented is outside the class. Everything in a class is indented, just like the code within a function, if statement, for loop, or any other block of code. Class names are usually capitalized, but this is only a convention, not a requirement. The name of this class is Student, and it doesn't inherit from any other class. The following statement makes a class with no attributes attached, and in fact, it's an empty namespace object:
0 Comments
Leave a Reply. |