Python -- class attributes/instance attributes

Source: Internet
Author: User

I. class attributes

The class property is only bound to the defined class. Class data attributes become useful only when more "static" data types are required. They are irrelevant to any instance.

1. Data attributes of the class

The data attribute is only a variable of the defined class. This property has been familiar to OO programmers, namely static variables or static data. They indicate that the data is bound to the class object to which they belong and does not depend on any class instance. Static members are generally used to track class-related values only.

>>> class C(object):...     foo = 100...>>> print(C.foo)100>>> C.foo = C.foo + 1>>> print(C.foo)101
2. Methods

>>> class MyClass(object):...     def myNoActionMethod(self):...             pass...>>> mc = MyClass()>>> mc.myNoActionMethod()
The myNoActiveMethod () method in the class MyClass is just a function defined as part of the class definition (which makes the method A Class Attribute ). This indicates that myNoActiveMethod is only applied to objects (instances) of the MyClass type.

Any call to myNoActiveMethod () itself like a function will fail:

>>> myNoActionMethod()Traceback (most recent call last):  File "
 
  ", line 1, in 
  
   NameError: name 'myNoActionMethod' is not defined
  
 
The NameError error is thrown. This indicates that myNoActionMethod is a method, indicating that it belongs to a class, rather than the name in the global space. This method cannot be called by class objects.

>>> MyClass.myNoActionMethod()Traceback (most recent call last):  File "
 
  ", line 1, in 
  
   TypeError: myNoActionMethod() missing 1 required positional argument: 'self'
  
 
To be consistent with OOP conventions, Python strictly requires that methods cannot be called without instances. Method must be bound to an instance before it can be called directly. A non-bound method may be called, but the instance object must be explicitly specified to ensure the call is successful. However, no matter whether it is bound or not, a method is a fixed attribute of its class, even if they are almost always called through an instance.

3. class attributes

You need to know the attributes of a class in two ways. The simplest is to use the dir () built-in function. In addition, the dictionary attribute _ dict _ of the category is used __.

>>> dir(MyClass)['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'myVersion', 'showMyVersion']>>> MyClass.__dict__mappingproxy({'__module__': '__main__', '__qualname__': 'MyClass', '__weakref__': , 'showMyVersion': 
 
  , '__dict__': , 'myVersion': '1.1', '__doc__': 'MyClass class definition'})
 
Dir () returns only one name-class table of the object's attributes, while _ dict _ returns a dictionary, and its key (key) is the attribute name, value is the data value of the corresponding property object.

4. Special class attributes

C. _ name __ Class C name (string)
C. _ doc __ Document string for Class C
C. _ bases __ Tuples of all parent classes of class C
C. _ dict __ Class C attributes
C. _ module __ Module of class C Definition
C. _ class __ Class corresponding to instance C

_ Name _ is the character name of the given class. It applies to situations where only strings (Class Object names) are needed, not the objects themselves. _ Doc _ is the document string of the class. It is similar to the document string of the function and module and must be followed by the string behind the first line. The document string cannot be inherited by the derived class, that is, the derived class must contain its own document string. _ Bases _ is used to process inheritance. It contains a tuples composed of all parent classes. The _ dict _ attribute contains a dictionary consisting of the data attributes of the class.

>>> MyClass.__name__'MyClass'>>> MyClass.__doc__'MyClass class definition'>>> MyClass.__bases__(
 
  ,)>>> print(MyClass.__dict__){'__module__': '__main__', '__qualname__': 'MyClass', '__weakref__': , 'showMyVersion': 
  
   , '__dict__': , 'myVersion': '1.1', '__doc__': 'MyClass class definition'}
  
 

Ii. instance attributes

An instance only has data attributes. It is the data values associated with an instance of a class. These values are independent of other instances or classes. When an instance is released, its attributes are also cleared.

1. "instantiate" instance attributes

You can set the attributes of an instance at any time after the instance is created, or in the code that can access the instance. The constructor _ init _ () is one of the key points for setting these attributes.

2. View instance attributes

The built-in function dir () can display class attributes and print all instance attributes:

>>> class C():...     pass...>>> c = C()>>> c.foo = 'roger'>>> c.bar = 'shrubber'>>> dir(c)['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bar', 'foo']
An instance also has a special attribute _ dict _, which is a dictionary composed of instance attributes:

>>> c.__dict__{'foo': 'roger', 'bar': 'shrubber'}

3. Special instance attributes

I. _ class __ Class for instantiating I
I. _ dict __ I 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.