Python Learning Notes (vii)-object-oriented advanced programming

Source: Internet
Author: User

I. Adding properties and methods to a class dynamically:

1. Dynamically add properties and methods to an instance:

The method that is bound to one instance has no effect on the other.

Class Student (object):    passs = Student () s.name = ' Michael ' # dynamically binds an attribute to an instance print S.namedef set_age (self, Age): # defines a function as Instance method    Self.age = age from    types import methodtypes.set_age = Methodtype (Set_age, S, Student) # Binds a method to an instance s.set_age ( 25) # Call instance method print S.age # test Result
2. Dynamically add properties and methods to a class:
Class Student (object):    passs = Student () from types import methodtypedef Set_score (self, score):    Self.score = Score    Student.set_score = Methodtype (Set_score, None, Student) s.set_score (+) Print S.score

Two. Using __slots__

Use __slots__ to limit the attributes that class can add:

Class Student (object):    __slots__ = (' name ', ' age ') # define the property name to allow binding with tuple S = Student () # Create a new instance S.name = ' Michael ' # binding attribute ' Name ' S.age = 25 # Binding attribute ' age '
Note: The properties defined by __slots__ only work for the current class and do not work on inherited subclasses.

Three. Using @property

@property is responsible for turning a method into a property invocation:

Class Student (object):    @property    def score (self):        return Self._score    @score. Setter    def score ( Self, value):        if not isinstance (value, int):            raise ValueError (' score must is an integer! ')        If value < 0 or value >:            raise ValueError (' score must between 0 ~ 100! ')        Self._score = value        s = Student () S.score = OK, actual conversion to S.set_score () print S.score # OK, actual conversion to S.get_score ()

Four. Multiple inheritance:

Python allows the use of multiple inheritance, for example: Dog inherits Animal and runnable

Class Animal (object):    passclass Runnable (object):    def run (self):        print (' Running ... ')        class Dog ( Animal, Runnable):    Pass
Five. Custom classes:

1. __str__

Equivalent to ToString in Java

Class Student (object):    def __init__ (self, name):        self.name = name        def __str__ (self):        return ' Student Object (name:%s) '% self.nameprint Student (' Michael ') # Student object (Name:michael)
2.__iter__

If a class wants to become a list or a tuple can be cycled (for. In), you must implement the __iter__ method, which returns an iterative object and constantly calls the next () method of the iteration object to get the next value of the loop:

Class Fib (object):    def __init__ (self):        self.a, self.b = 0, 1 # Initializes two counters A, a    def __iter__ (self):        return The self # instance itself is an iterative object, so return your    def next:        self.a, self.b = self.b, SELF.A + self.b # Calculates the next value        if SELF.A > 10000 0: # Exit the condition of the loop            raise Stopiteration ();        Return SELF.A # Returns the next value for    N in Fib ():    print N
3.__getitem__


4.__getattr__

5.__call__

Six. Use meta-classes:

Python Learning Notes (vii)-object-oriented advanced programming

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.