Python object-oriented instance attributes and class attributes

不言
Release: 2018-04-14 10:32:36
Original
1271 people have browsed it

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
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template