Python3 Learning V-Bombs: Classes and object-oriented

Source: Internet
Author: User

For object-oriented always mention that everything is object. Like a profound feeling. Next look at Python's object-oriented example
Create an Object
Class Person:type = ' Person ' def __init__ (self, name = ' Noname '): Self.name = namedef Hello (self):p rint ("Hello, I ' m" + self . Name) >>> Mike = person (' Mike ') >>> Mike.hello () Hello, I ' m Mike there is a default constructor for an object, and of course we can rewrite the __init__ To change the construction method. Constructor methods are called automatically when an object is created.
Properties of the class
Class properties: Type and Default Class Property instance properties: Name is easy to understand, instance properties are only generated when a class object is created, and class properties are class-intrinsic property class property Access can be accessed via Dir (person) or person.__dict__ View while instance properties can be viewed by mike.__dict__ the basic class properties: __doc__ functions of the document. The string, if not, is none writable __name__ function name writable __module__ defines the module name of the function, or, if there is no corresponding module name, for none__bases__ returns the class of all the parent classes of that class __class__ instance corresponding to the classes __ The Dict__ class's properties consist of a dictionary >>> class person: "Michael Scofield's File" name = ' Michael ' Def __init__ (self, age): Self.age = age>>> person.__doc__ "Michael Scofield ' s file" >>> person.__name__ ' person ' >>> person.__ Bases__ (<class ' object ') >>> person.__dict__mappingproxy ({' __dict__ ': <attribute ' __dict__ ' of ') Person ' objects>, ' __doc__ ': "Michael Scofield's File", ' __weakref__ ': <attribute ' __weakref__ ' of ' person ' objects ' Name ': ' Michael ', ' __module__ ': ' __main__ ', ' __init__ ': <function person.__init__ at 0x00000000033dbbf8>}) >>> A = person (+) >>> a.__class__<class ' __main__. Person ' >
Inherited apps
Subclasses can inherit to get the properties of the parent class, and can have their own class properties >>> class Bird:def __init__ (self): Self.hungry = Truedef eat (self): if self.hungry :p rint (' eat something ') Self.hungry = Falseelse:print (' Too fat ') >>> class SongBird (Bird):d ef __init__ (self, song): Self.song = Songdef sing (self):p rint (self.song) >>> a = SongBird (' hello ') >>> a.sing () Hello we often encounter subclasses that have similar functions to the parent class, but not quite the same. You can create your own function by rewriting it, and when you run the function, you will find the function in the subclass, and if you no longer look for it from the parent class, such as the __init__ method in the previous example overrides but there is a problem,>>> a.eat () Attributeerror: ' SongBird ' object has no attribute ' hungry ' because there is no call to the parent class of Init to make the properties of the hungry disappear, the use of super can eliminate this effect. >>> class SongBird (Bird):d ef __init__ (Self, song): Super (SongBird, self). __init__ () Self.song = song>> > a.eat () Eat something>>> a.eat () Too Fat Here's super is not a function, but a class, Represents the parent of a SongBird and passes in its own object self, of course, there is another workaround before the super, which is to call the parent class function >>> class SongBird (Bird):d ef __init__ (self, song) : bird.__init__ (self) Self.song = song but as soon as the parent class is changed, it is necessary to change the parent class in the class as in the previous example Bird, so it is best to use super
Class method (similar to operator overloading)
The __init__ in the example above is a construction method that is called automatically when a new class object is created, and there are many class methods available that cover almost all python operators. Let's take a look at common class methods. >> Basic Method:1> __init__ (self[, arg1, ...]) constructor, called after the function object is created, no return value 2> __new__ (self[, arg1, ...]) constructor, create function Object function, The return value is that the object is generally __new__ not used unless the subclass requires an immutable type. 3> __del__ (self) is called when an object is deleted and is generally not changed because the time the object was deleted is determined by the python itself 4> __str__ (Auto) returns the string to be printed (more user-friendly), with the built-in STR () and print5> _ _REPR__ (self) Returns the compiler-friendly string, slightly different for detail handling repr and str: the STR () function is meant to return representations of values which a Re fairly human-readable, while repr () are meant to generate representations which can be read by the interpreter (or would Force a SyntaxError if there are not equivalent syntax). For objects which there is a particular representation for human consumption, str () would return the same value as REPR () . Many values, such as numbers or structures like lists and dictionaries, with the same representation using either function . Strings and floating point numbers, in particular, with a distinct representations.6> __FORmat__ (self, Format_spec) calls format () to run the function 7> the __call__ (self, *args) class can be called as a function, which runs whenever the class object is called, equivalent to overloading the parentheses 8> __len__ ( Self) runs the function >> comparison method when you call Len ():1> __lt__ (self, obj) overload <2> __le__ (self, obj) overload <=3> __eq__ (self, OB j) Overload ==4> __ne__ (self, obj) overloads the!=5> __gt__ (self, obj) overload of the __ge__ (self, obj) overload if it is not overloaded, > defaults to >= T; object Exchange, vice versa >>> class Person:def __init__ (self, age): Self.age = Agedef __lt__ (self, b): Return Self.age-b.agede F __gt__ (self, b): return self.age > b.age>>> a = person (1) >>> B = Person (2) >>> a > Bfalse >>> a < b-1>>> b > atrue>>> B < a1>> property action method (note that the following attr properties are represented by a string) 1> __getattr __ (self, attr) Gets a property that is called when it is not successful, and is called when using GetAttr () 2> __setattr__ (self, attr, value) when used with the Python3 test, even though the Get property is successfully called) Called when setting a property or creating a new property, using SetAttr () when called >>> class Person:def __init__ (self, age): Self.age = Agedef __getattr__ (self, attr) :p rint (' __getattr__ used ') def __setattr__ (self, attr, val):p rint (' __setattr__ used ') >>> a = person (1) __setattr__ used>>> a.age__getattr__ used>> > a.age=1__setattr__ used3> __delattr__ (self, attr) Delete property, use Delattr () to invoke 4> __getattribute__ (self, attr) Gets the property, regardless of whether the access succeeds or not, calls the 5> __get__ (self, attr) descriptor, gets the property 6> __set__ (self, attr, value) descriptor, sets the property 7> __delete__ (self, attr) Descriptor Delete attribute above three temporarily do not understand its usage >> numeric operation symbol overload 1> __add__ (self, other) Overloads +2> __sub__ (self, other) Overloads -3> __mul__ (self, Other) overload *4> __truediv__ (self, other) Overloads/5> __floordiv__ (self, other) Overloads//6> __mod__ (self, other) overloads%7> __div Mod__ (self, other) overload Divmod (A, B) #返回元组 (a//b, a%b) 8> __pow__ (self, other[, modulo]) Heavy duty pow (A, b) **9> __lshift__ (self , other) overload <<10> __rshift__ (self, other) overload >>11> __and__ (self, other) overload &12> __xor__ (self, Other) overloaded ^13> __or__ (self, other) overloads | ADD1: If you add R to the overloaded operator function above, that is, __radd__ (self, and other), it means that its parameter position is swapped. For example, to calculate the expression x-y, Y is a class instance that defines the method __rsub__ (), then when x.__sub__ (y) returns notimplementedY.__RSUB__ (x) is called. ADD2: If I is added before the overloaded operator function above, that is, __iadd__ (self, other), the overloaded character is + =. And so on 14> __neg__ (self) reload minus -15> __pos__ (self) reload plus +16> __abs__ (self) reload abs () 17> __invert__ (self) overload ^ Cast type 18> __complex__ (self) overload complex () #表示复数类型19 > __int__ (self) overload int () 20> __float__ (self) Overload float () 21> _ _round__ (self) Overloads round () >> sequence operator overloads the number of items in the 1> __len__ (self) Sequence 2> __getitem__ (self, index) when you get the sequence, call 3> __ Setitem__ (self, Index, value) when you set a sequence item or create a new item, call 4> __delitem__ (self, index) when you delete a single sequence element when you call >>> class Class:def __ init__: self.student = [' LWT ', ' CYL ', ' Bash ']def __len__ (self):p rint (' Len called ') return Len (self.student) def __ Getitem__ (self, Index):p rint (' getitem called ') return self.student[index]def __setitem__ (self, Index, value):p rint (' SetItem called ') self.student[index] = Valuedef __delitem__ (self, Index):p rint (' Delitem called ') del Self.student[index ]>>> a609 = Class () >>> len (a609) Len called3>>> a609[1]getitem called ' CYL ' >>> a609[2] = ' Bug ' SetItem called>>> a609<__main__. Class object at 0x0000000003c3fd30>>>> del A609[2]delitem called is actually equivalent to overloading the list with its operations. Above, probably includes most of the overloaded types.

  

Python3 Learning V-Bombs: Classes and object-oriented

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.