The Python class 2--class dynamic Add method and slots (GO)

Source: Internet
Author: User

Let's talk about the difference between the class Add property method and the instance add property and method,

A class-add attribute is added to a class-global attribute (said to be called a static property), and every instantiation of the class later has this property. Adding a method to a class is also true for each instantiation of the class, but it is said to be a dynamic method. However, adding an attribute to the instance, the scope is the instance, is not the same as the class (it is said that this property is called dynamic property).

Instances of the Python class can add properties dynamically. As an example, declare a Class A

>>> class A (object):
... def __init__ (self):
.. print ' A '

Instantiate an A,

A=a ()

Now give a plus a Name property

>>> a.name= ' AAA '
>>> A.name
' AAA '

Now add a method to Class A

>>> def func ():
... print ' func '

>>> A.func=func
>>> A.func
<bound method A.func of <__main__. A Object at 0x7f323dcb8750>>
>>> A.func ()
Func

So what can slots do? Slots can prevent arbitrary addition of an attribute to an instance.

>>> class A (object):
... def __init__ (self):
... print ' func '
... __slots__= (' name ')

When we modify the Name property, name is modified to AAA,

>>> A=a ()
>>> a.name= ' AAA '
>>> A.name
' AAA '

But when we want to add an age attribute dynamically, we get an error.

>>> a.age=16
Traceback (most recent):
File "<stdin>", line 1, in <module>
Attributeerror: ' A ' object has no attribute ' age '

But when you want to add a property to the class as follows, the slots cannot be limited.

>>> a.age=3
Here to say, if the subclass inherits the parent class, the parent class has the slots, this slots is in the subclass does not have the function, if wants to use, can only rewrite slots, achieves the desired result.

The Python class 2--class dynamic Add method and slots (GO)

Related Article

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.