URLhttps://learnscript.net/en/python/classes/
    Copy LinkGo to Instructions  Example

    Introduction to Python Classes; Define and Use Python Classes

    Beatme CodeBY-NC-ND
    16:59 read·2209 words· published

    Define Python Classes

    In Python, classes are usually defined in modules, and the basic form of their syntax is as follows.

    class <classname>:
        <docstring>
        <block>

    classname part

    classname is the name of the Python class, which needs to conform to Python's identifier specification and cannot use keywords or reserved keywords.

    docstring part

    docstring is the documentation string for a Python class that contains a description of the class; this is not a mandatory requirement; a Python class can have no documentation string.

    block part

    block is the body code of the Python class, and both it and docstring need to be indented with some sort of whitespace character to indicate that they belong to the Python class.

    Python Class Attributes

    Similar to modules, the variables (fields), properties, methods (functions), and so on, defined in Python classes are called attributes. Attributes can be accessed through expressions of the form c.name, c.name=value, where c is the Python class or object (an instance of the class), name is the attribute (name, identifier), and value is the attribute’s new value.

    Of course, the attributes of Python classes can be called variables, methods, and properties, and there’s nothing wrong with that.

    Here’s a simple Python class, Apple, containing variables and static methods.

    apple.py
    # A simple class Apple
    class Apple:
    	# Variable variety
    	variety = 'Ordinary apples'
    	# Static method show
    	@staticmethod
    	def show():
    		print(Apple.variety)
    
    # Assign a value to the attribute variety Apple.variety = 'Stone apples' # Call the show method Apple.show()
    Stone apples

    Python's Class Attributes and Instance Attributes

    In Python, the attributes of classes are categorized into class attributes, which are defined either directly in the Python class, or through parameters that represent the class (generally agreed upon as cls), and instance attributes, which need to be defined through the Python instance, or through parameters that represent the instance (generally agreed upon as self).

    Python class attributes can be accessed through classes or parameters representing classes (generally agreed upon as cls), and Python instances or parameters representing instances (generally agreed upon as self), while Python instance attributes can only be accessed through instances or parameters representing instances.

    Add transient attributes to Python classes and instances

    Without restriction, a Python class or instance can add temporarily existing attributes simply by using an expression of the form c.name=value, where c is the class or instance, name is the attribute (name, identifier) to be added, and value is the value of the attribute.

    How do I view all the attributes of a Python class or instance?

    The special attribute __dict__ of Python classes, instances, and objects lets you view all the attributes that correspond to them, including private and transient attributes. The attribute __dict__ is a dictionary object, where the key of a key-value pair represents the name of a attribute, and the value of the key-value pair represents the specific content of the attribute.

    It should be noted that the key-value pairs in a Python class’s __dict__ and an instance’s __dict__ do not overlap, and that a class’s __dict__ contains only class attributes and an instance’s __dict__ contains only instance attributes, although it is not excluded that there may be attributes with the same name belonging to the Python class and instance, respectively.

    We adapt the previous example by adding a constructor to the class Apple to define the instance variable weight, and by adding the transient class variable price through the class, and the transient instance variable price through the instance, and then output and display the __dict__ attribute of the Apple class and instance.

    apple.py
    # A simple class Apple
    class Apple:
    	# …
    	# Constructor
    	def __init__(self, w):
    		# The instance variable weight is defined by self, which represents the instance
    		self.weight = w
    # …
    # Add a class variable to the Apple class and then display all the attributes of the Apple class
    Apple.price = 10
    print(Apple.__dict__)
    # Add an instance variable to the instance and then display all the attributes of the instance
    apple = Apple(100)
    apple.price = 30
    print(apple.__dict__)
    {'__module__': '__main__', 'variety': 'Stone apples', 'show': <staticmethod(<function Apple.show at >)>, '__init__': <function Apple.__init__ at >, '__dict__': <attribute '__dict__' of 'Apple' objects>, '__weakref__': <attribute '__weakref__' of 'Apple' objects>, '__doc__': None, 'price': 10}
    {'weight': 100, 'price': 30}

    Class attributes cannot be assigned or modified directly by Python instances

    You can read class attributes via Python instances or parameters that represent instances (such as self), but you can’t do assignments, which would be considered adding new attributes to the Python instance, which is similar to trying to assign module-defined variables directly in a function.

    In the following code, writing apple.variety is equivalent to reading Apple.variety, and writing apple.variety='Extra large apple' is equivalent to adding the instance variable variety to the instance apple, and Apple.variety will not be modified.

    apple.py
    # …
    # Create an instance of the Apple class
    apple = Apple(30)
    # Access the class variable variety through the instance
    print(apple.variety)
    
    # The following assignment statement will define a new instance variable variety for the instance apple.variety = 'Extra large apple' # Therefore, the class variable variety does not change print(Apple.variety)
    Stone apples
    Stone apples

    Define Variables for Python Classes

    The variables (fields) of Python classes are categorized into class variables and instance variables, which are one of the attributes of Python classes. You can define a class variable or an instance variable in the following form, where cls is the parameter that indicates a Python class and self is the parameter that indicates a Python instance.

    [cls|self.]<variablename>=<value>

    variablename part

    variablename is the name of the variable, which needs to conform to Python's identifier specification, and cannot use Python keywords or reserved keywords.

    value part

    value is the value corresponding to the variable.

    student.py
    # A class representing a student
    class Student:
    	# Class variable count
    	count = 0
    	# Constructor
    	def __init__(self, n, a):
    		# Instance variables name, age
    		self.name = n
    		self.age = a

    Define Methods for Python Classes

    The methods (functions) of Python classes are one of the attributes of Python classes that have similarities to functions in Python modules and can be defined in the following form, where @classmethod means defining a class method and @staticmethod means defining a static method.

    [@classmethod|@staticmethod]
    def <methname>(<parameterlist>)
        <block>

    methname part

    methname is the method name, which needs to conform to Python's identifier specification, and cannot use Python keywords or reserved keywords.

    parameterlist part

    parameterlist is the parameter list of the method, which defines all the parameters of the method, separated by ,.

    block part

    block is the body code of the method and needs to be indented with some sort of whitespace character to indicate that it belongs to the method.

    If the decorators ‘@classmethod’ or ‘@staticmethod’ are not specified, the defined method is called an instance method, and its first parameter, generally named self, denotes the Python instance itself, through which instance attributes can be read or written, or class attributes can be read. The self parameter needs to be omitted when the instance method is called through a Python instance, and given when the instance method is called through a Python class.

    If the decorator @classmethod is specified, the method defined is a class method, whose first parameter, typically named cls, denotes the Python class itself, and through which class attributes, but not instance attributes, can be accessed. The cls parameter needs to be omitted when calling class methods, whether through a Python instance or a Python class.

    If the decorator @staticmethod is specified, the method defined is a static method, which doesn’t have special parameters like instance and class methods, so it can’t access Python instance attributes or class attributes via special parameters.

    Methods defined directly in Python classes are class attributes

    In fact, methods defined directly in Python classes are class attributes, not instance attributes, and whether they are called instance, class, or static methods, the main difference between them is whether the first parameter indicates a Python instance or a Python class, or neither.

    Because they are all class attributes, instance methods, class methods, and static methods can be called from both Python instances and Python classes.

    Functions

    For an in-depth look at Python functions, you can check out the article Introduction to Python Functions, Parameters, Return Values; Define and Call Python Functions.

    Next, we add some methods to the previous Student class and call them via class or instance, respectively.

    student.py
    # A class representing a student
    class Student:
    	# …
    	# Instance method info
    	def info(self):
    		print(f'{self.name} {self.age}')
    
    # Class method show @classmethod def show(cls): # Read the class variable count via the parameter cls print(f'{cls.count} student(s) in total') # Static method set_count @staticmethod def set_count(c): # The class variable count can only be accessed through classes Student.count = c print(f'The number of students is set to {Student.count}')
    student = Student('Jack', 13) # Call the instance method info student.info() Student.info(student) # Call the static method set_count student.set_count(-100) Student.set_count(100) # Call the class method show student.show() Student.show()
    Jack 13
    Jack 13
    The number of students is set to -100
    The number of students is set to 100
    100 student(s) in total
    100 student(s) in total

    Define Private Attributes for Python Classes

    Python class attributes, whether they are Python class attributes or instance attributes, are private if their identifiers begin with __ and can be accessed only within the Python class that defines them, not externally or in derived classes.

    Identifiers for private attributes of Python classes are automatically prefixed

    Private attributes that begin with __ have their identifiers automatically prefixed with a specific prefix, which is a combination of _ and the class name, as can be seen in the __dict__ attribute of a Python class or Python instance. The identifier change only concerns the class that defines the attribute, which is why you can’t use a private attribute externally or in a derived class, because you’re accessing something that doesn’t exist.

    Of course, with knowledge of the above rules, private attributes may no longer be private and can simply be accessed using identifiers with specific prefixes.

    The following class Teacher defines two private instance variables with the prefix _Teacher automatically added to their identifiers.

    teacher.py
    # A class representing a teacher
    class Teacher:
    	# Constructor
    	def __init__(self, n, a):
    		# Private instance variables __name, __age
    		self.__name = n
    		self.__age = a
    
    teacher = Teacher('Invisible Man', 30) # Show all the attributes of the Teacher instance print(teacher.__dict__) # Access the private variable __name in a special way print(teacher._Teacher__name)
    {'_Teacher__name': 'Invisible Man', '_Teacher__age': 30}
    Invisible Man

    Define Constructors for Python Classes

    The constructor of a Python class is an instance method called __init__. As with other instance methods, the first parameter of the __init__ method is typically named self, denoting the Python instance itself, and the rest of the parameters can be used to initialize instance variables or to perform other operations, as the Student class does.

    Of course, in the official Python documentation, there is no such thing as a constructor; __init__ means only initialization, and it is called after the Python instance is created.

    Create Instances of Python Classes

    To create an instance of a Python class, you use the class name and (), which contains a set of parameters that generally correspond to the parameters of the __init__ method (you need to omit self). For example, previously we created an instance of the Student class using Student('Jack',13).

    How do I check the type corresponding to a Python instance?

    Information about the type (class) corresponding to a Python instance (object) can be obtained through the __class__ property of that instance (object), the return value of which is a type object.

    For defined Python classes, the return value of the __class__ property is shown as <class 'type'>, which means that the defined Python class can be treated as an instance whose type is type.

    student.py
    # …
    # Get the type information of the Student class and the previously created instance student
    print(student.__class__)
    print(Student.__class__)
    <class '__main__.Student'>
    <class 'type'>

    Namespaces for Python Classes

    It stands to reason that Python classes should have their own namespaces to avoid identifiers for attributes the class has conflicting with other identifiers.

    Documentation Strings for Python Classes

    Similar to Python functions and modules, Python classes have a documentation string stored in __doc__, which is a string literal, the first valid line of code for the class, which can be concatenated in close proximity or with whitespaces, and does not contain the content or operations that need to be computed.

    hello.py
    # A strange class
    class Hello:
    	"""Hello, """'Python!'

    Python Nested Classes

    A nested class is a Python class defined within another class, function, or method. Because of the general principle of scope, the accessibility of a defined nested class is equivalent to that of a Python variable defined in the same namespace.

    The nested class World, defined below, has accessibility equivalent to the class variables in Hello.

    hello.py
    # A strange class
    class Hello:
    	# …
    	# A strange nested class
    	class World:
    		pass

    Catalogs

    Source Code

    src/en/classes·codebeatme/python·GitHub