Python Learning Notes-----class __python

Source: Internet
Author: User

1. Simple example

In general, the Python class and C + + classes are the same. There's only a slight difference in grammar, so this is mainly about grammar. Let's start with a simple example:

Class Base (object):
    static_v =
    def __init__ (self):
        self.x = 0
        self.y = 0
        self.z = 0
        print ' AA A ', self.x, Self.y, self.z
    def PR (self):
        print self.x, SELF.Y, Self.z

class child (Base):
    def __init__ ( Self):
        base.__init__ (self)
        SELF.A = 1
        self.b = 1
        self.c = 1
        print ' BBB ', self.x, Self.y, self.z , SELF.A, self.b, SELF.C 
    def PR (self):
        print self.x, Self.y, Self.z, SELF.A, self.b, SELF.C

For example, Python's basic class syntax should all be included, and most of the ideas are similar to C + +.

But one thing to emphasize is the __init__ function, in C + +, the constructor of the subclass is called the constructor of the parent class, which is called automatically and does not need to be called explicitly. But not in Python, when the subclass __init__ is overridden, the parent class __init__ is not invoked, and if you want to call it, it needs to be like the example.

2, class method and static method

Class Test:
    @staticmethod
    def SM ():
        print "Static method is called ..."
        
    @classmethod
    def cm (CLS):
        print ' class method is called ... ', cls.__name__
        
Test.sm ()     
test.cm ()   

It seems that the class method and the static method seem to be the same, because it's all about the class (of course, it can be invoked through an instance), but I think Python does this by confusing the class with the instance, so I understand that the class method and the static method are exclusive to the class, and the big difference between the two is that Class methods need to pass the parameter CLS, so that the properties of the class can be invoked at will by the class method.


3, some of the class properties that will be used

Print test.__doc__ print
test.__bases__ print
test.__name__
print test.__module__

4. Built-in functions for classes and instances

Issubclass (Sub, SUP): Determining parent-child class relational functions

Isinstance (example, Class): To determine whether a class of instances, can be judged by the built-in type (int, float, etc.)

hasattr (), GetAttr (), SetAttr (), Delattr (): the Hasattr () function is Boolean, and its purpose is to determine whether an object has a specific attribute, Typically used to access a property before checking. The GetAttr () and setattr () functions get and assign properties to objects, and GetAttr () throws Attributeerror exceptions when you try to read a nonexistent property, unless you give the optional default argument. SetAttr () will either add a new attribute or replace an existing attribute. The delattr () function deletes an attribute from an object.

>>> class MyClass (object):
... def __init__ (self):
... self.foo = ...
>>> myinst = MyClass ()
>>> hasattr (myinst, ' foo ')
True
>>> getattr (Myinst, ' Foo ')
>>> hasattr (myinst, ' Bar ') False
>>> getattr (myinst, ' Bar ') Traceback (most Recent call last):
File "<stdin>", line 1, in?
GetAttr (myinst, ' Bar ')
Attributeerror:myclass instance has no attribute ' bar '
>>> getattr (c, ' Bar ', ' oops! ')
' Oops! '
>>> setattr (myinst, ' bar ', ' my attr ')
>>> dir (myinst)
[' __doc__ ', ' __module__ ', ' bar ', '] Foo ']
>>> getattr (myinst, ' Bar ') # Same as Myinst.bar #等同于 myinst.bar
' My attr '
>>> Delattr (myinst, ' foo ')
>>> dir (myinst)
[' __doc__ ', ' __module__ ', ' Bar ']
>>> Hasattr (myinst, ' foo ')
False

super (type, obj): gives the parent class object of the current class, such as Super (Myclass,self). __init__ () so that the parent class is not explicitly given.

If obj is an instance, Isinstance (Obj,type) must return true.

If obj is a class or type, Issubclass (Obj,type) must return True

VARs (): method and Dict similar

Class Test (object):
    def __init__ (self):
        self.a = 0
        self.b = 0
        
t = Test ()
print dir (t)
print t.__ dict__
print VARs (t) 

[' __class__ ', ' __delattr__ ', ' __dict__ ', ' __doc__ ', ' __format__ ', ' __getattribute__ ', ' __hash__ ', ' __init__ ', ' __ module__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __ Subclasshook__ ', ' __weakref__ ', ' A ', ' B ']
{' A ': 0, ' B ': 0}
{' A ': 0, ' B ': 0}

Summary: Methods to get an instance or class property are, __dict__, VARs (), dir (), the first two basically the same, and the return of the dictionary, the latter returned the list, dir is more than the previous two returned to some of the content of Python automatically added attributes, If you just want to get a custom attribute, just use the first two to make it OK.


5, with special methods to customize the class




A class that overloads __str__ (for print) and the plus sign

Class Time60 (object):
    ' time60-track hours and minutes '

    def __init__ (self, HR, min):
        ' Time60 constructor-ta Kes hours and minutes '
        self.hr = hr
        self.min = Min

    def __str__ (self):
        ' time60-string representation ' 
  return '%d:%d '% (self.hr, self.min)

    __repr__ = __str__

    def __add__ (self, Other):
        ' time60-overloading t He addition operator ' return
        self.__class__ (self.hr + other.hr,
            self.min + other.min)

    def __iadd__ (self , other):
        ' time60-overloading in-place addition '
        self.hr + + other.hr
        self.min + + other.min
        return Self

An example of an overloaded iterator next:

Class Anyiter (object):
    def __init__ (self, data, Safe=false):
        self.safe = safe
        Self.iter = iter (data)
    
    def __iter__ (self): return
        self
    
    def next (self, howmany=1):
        retval = [] for
        Eachitem in range (Howmany): C8/>try:
                retval.append (Self.iter.next ())
            except stopiteration:
                if Self.safe:
                    break
                Else:
                    raise return
        retval
    
    

a = Anyiter (range)
i = iter (a) for J-in
range (1, 5):
    print J, ': ', I.next (j)






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.