Home >Backend Development >Python Tutorial >Python object-oriented instance attributes and class attributes

Python object-oriented instance attributes and class attributes

不言
不言Original
2018-04-14 10:32:361309browse

The content shared with you in this article is about the object-oriented instance attributes and class attributes of Python. It has a certain reference value. Friends in need can refer to it.

Since Python is a dynamic language, according to the class You can create an instance and bind any properties.

The way to bind attributes to an instance is through the instance variable, or through the self variable:

class Student(object):
    def __init__(self,name):
        self.name = name

s = Student('jeff')
print(s.name)
#jeff

When we define a class attribute, although this attribute is classified as all, all of the class Instance

can be accessed. Let’s test it:

>>> class Student(object):
...     name = 'Student'
...
>>> s = Student()
>>> print(s.name)
Student
>>> print(Student.name)
Student
>>> s.name = 'jeff'
>>>
>>> print(s.name)
jeff
>>> print(Student.name)
Student
>>> del s.name
>>> print(s.name)
Student
>>> print(Student.name)
Student

As can be seen from the above example, when writing a program, never use the same name for instance attributes and class attributes, because instance attributes with the same name will block the class attributes. But when you delete the strength attribute and use the same name again, what you access will be the class attribute

Related recommendations:

Python object-oriented obtaining object information

Python object-oriented inheritance and polymorphism

The above is the detailed content of Python object-oriented instance attributes and class attributes. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn