Python object-oriented-class attributes and instance attributes

Source: Internet
Author: User

Python object-oriented-class attributes and instance attributes

Python object-oriented-class attributes and instance attributes

I. instance attributes

Python is a dynamic language. You can bind attributes to instances created based on classes.

>>> Class Student (object ):
... Def _ init _ (self, name ):
... Self. name = name # attributes required by each instance
...
>>> S = Student ('jack ')
>>> S. score = 90 # Any property bound
>>> S. name
'Jack'
>>> S. score
90

Ii. class attributes

Define attributes directly in the class. This attribute is a class attribute.StudentClass.

>>> Class Student (object ):
... Name = 'jack' # class attributes
...
>>> Student. name # obtain class attributes
'Jack'
>>> S = Student ()
>>> S. name # Get class attributes
'Jack'
>>> S. name = 'Mike '# Add instance attributes
>>> S. name # obtain instance attributes
'Mike'
>>> Student. name # obtain class attributes
'Jack'

When writing a program, do not use the same name for the instance attributes and class attributes, because the instance attributes with the same name will block the class attributes, but after you delete the instance attributes, use the same name to access the class attributes.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.