In Python, a class defines an object. It contains information about the object action method, including its name, method, attribute, and event, the following article will further learn about the Python class, which greatly improves the variable data.
Objects can use common variables that belong to objects to store data. Variables belonging to an object or Python class are called fields. Objects can also use functions that belong to a class. Such functions are called class methods. Fields and methods can be collectively called class attributes. There are two types of domains-the method that belongs to each instance object) is called an instance variable; the method that belongs to the class itself is called a class variable.
There is only one special difference between class methods and common functions-they must have an additional first parameter name, but you do not assign a value to this parameter when calling a method, python provides this value. This special variable refers to the object itself, which is named self by convention.
The class and object methods can be understood as follows:
- Class Person:
- Population=0
- Def _ init _ (self, name ):
- Self. name= Name
- Person. population + = 1
- Def _ del _ (self ):
- Person. population-=1
- IfPerson. population= 0:
- Print ("I am the last one ")
- Else:
- Print ("There are still % d people left." % Person. population)
- Def sayHi (self ):
- Print ("hi my name is % s" % self. name)
- Def howMany (self ):
- IfPerson. population= 1:
- Print ("I am the only person here ")
- Else:
- Print ("we have % d persons here." % Person. population)
- S=Person("Jlsme ")
- S. sayHi ()
- S. howMany ()
-
- K=Person("Kalam ")
- K. sayHi ()
- K. howMany ()
-
- S. sayHi ()
- S. howMany ()
- Output:
- Hi my name is jlsme
- I am the only person here
- Hi my name is kalam
- We have 2 persons here.
- Hi my name is jlsme
- We have 2 persons here.
Population is a Python class variable. The name variable belongs to the object and uses self to assign values. Therefore, it is the variable of the object. We can see that the _ init _ method uses a name to initialize the Person instance. In this method, we increase population by 1 because we have added a person.
We can also find that the value of self. name is specified based on each object, which indicates the essence of self. name as the object variable. Remember, you can only use the self variable to refer to the variables and methods of the same object. This is called attribute reference.
- How to embed Python into C ++ applications?
- In-depth discussion of Ruby and Python syntax comparison
- Introduction to Python
- Python Learning Experience: version, IDE selection and coding Solutions
- Analysis of Python GIL and thread security