The next thing you learn about object-oriented programming is that the basics are not recorded and only some Python-specific or advanced features are recorded.
Http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 0014318645694388f1f10473d7f416e9291616be8367ab5000
1. Definition of class
The definition class uses the class keyword, followed by the name (capitalized), followed by which class inherits (all classes eventually inherit object).
An instance can be created by adding arguments to the class name. You are free to bind properties to an instance. Some properties that must be bound are written in the class, and the property values are bound by the __init__ method at initialization time.
The difference between a function in a class and a normal function is that the first argument is self, which represents the created instance itself (which is not required at the time of invocation, and the Python interpreter passes the instance variable in itself).
class Person (object): def __init__ (self, Name, age): self.name = name Self.age = Age def say_hello (self ): print ("Hello, my name is%s and I ' m%s years old"% (Self.name, self.age)) Tom = person (' Tom ', ') Tom.say_hello () # H Ello, my name is Tom and I ' m-years old
2. Access Restrictions
If you want the internal properties of the class to not be externally accessible, you can add two _ to the front, which becomes a private variable.
If you want to access/modify variables externally, you can add methods such as Get_xxx, set_xxx, and so on.
Before and after there are two _ is a special variable, can be directly accessed.
The variable that begins with a _ is a "conventional" private variable that can be accessed externally, but not done.
Variables that begin with two _ are also accessible, assuming the class name is person and the variable name is __name, and in the current version of Python, the __name variable can be accessed externally through _person__name. However, it is not recommended to do so, in addition to the specification, different versions of the Python interpreter will change the __name to a different variable name.
3. Inheritance and polymorphism
object is the root (base class), and any class can be traced back to object.
The meaning of polymorphism (suppose there is a class animal, there is a Run method):
For a variable, we just need to know that it is a animal type, and you can call the run () method without knowing exactly what its subtype is, and that the run () method of the call is on the animal, the dog, or the cat object, determined by the exact type of the object at run time. That is, the caller just calls, regardless of the details, when a new subclass of animal is added, simply make sure that the run () method is written correctly and does not control how the original code is invoked. This is the opening and closing principle:
Open to extensions: Allows the addition of animal subclasses;
Closed for modification: You do not need to modify a function that depends on the animal type.
For a static language (such as Java), if you need to pass in the animal type, the incoming object must be a animal type or its subclass, and for Python, a dynamic language, you do not necessarily need to pass in the animal type, just make sure that the incoming object has a run () method. This is the "duck type" of dynamic language, it does not require strict inheritance system, an object as long as "look like a duck, walk like a duck", it can be regarded as a duck.
Python supports multiple inheritance, often using the mixin design pattern. For example, Python comes with two types of network services, TCPServer and Udpserver, and a multi-process or multithreaded model must be used to serve multiple users at the same time, both of which are provided by Forkingmixin and ThreadingMixIn. By combining, we can create the right services.
4. Get Object Information
The type () function can get the types of objects.
For classes that have an inheritance relationship, you can use the Isinstance () function. The function determines whether an object is the type itself, or is located on the parent inheritance chain of that type.
Ininstance () also supports judging whether a variable is one of some types:
Isinstance ([1, 2, 3], (list, tuple))
Dir () is used to get all the properties and methods of an object, which returns a list containing a string.
The method is also an attribute, and if you want to know what methods are, you can use callable () to judge.
GetAttr (), SetAttr (), and hasattr () are used to manipulate the properties and functions of an object, such as:
# obj Object has property xhasattr (obj, ' x ') # Set a property ysetattr (obj, ' y ', 20) # Gets the property ygetattr (obj, ' y ') # Gets the property Z (if you try to get a property that does not exist, there will be an error, So you can give a default value) GetAttr (obj, ' z ', 404)
5. Instance properties and Class properties
The method for binding properties to an instance is through an instance variable, or through the self variable.
If you want to bind a property to the class itself, you can define the attribute directly in class.
Class attribute instances can also be used, but only if the instance does not have this property.
Personally, the better way is that the instance and Class properties do not use the same name, and when the class attribute is obtained, it is obtained by the class name, not by the instance name.
6. Using @propery
@property adorners can turn a method into a property call.
To turn a getter method into a property assignment, just add a @property to it. At this time @property itself created another adorner @xxx.setter, where xxx is the property name, is responsible for a setter method into a property assignment.
You can also define only getter methods so that this property is a read-only property.
Class Student (object): @property def Birth (self): return Self._birth @birth. Setter def birth ( Self, value): Self._birth = value @property def-age (self) : return 2016-self._births = Student () S.birth = 1990s.births.age
7. Custom Classes
Python's class has a number of special-purpose functions, such as __xxx__, that can help us customize the class.
__len__
Defines the class of the __len__ () method, which can act directly on the Len () function, which is the __len__ () method that invokes the object inside the Len () function.
__slots__
We can bind an instance to an attribute, or we can bind a method to an instance:
def set_age (self, Age): self.age = agefrom types Import methodtypes.set_age = Methodtype (Set_age, s) # where S is an instance of a class
This method of binding can only be valid for the current instance, and if you want all instances to be valid, you could bind the method to the class:
Person.set_age = Set_age
But what if we want to restrict the properties of an instance? When defining class, you can define a special __slots__ variable to limit the attributes that the class instance can add:
Class Student (object): __slots__ = (' name ', ' age ')
The properties defined by __slots__ only work on the current class instance, have no effect on the class, and do not work on instances of inherited subclasses. Unless __slots__ is also defined in a subclass, the class allows the defined property to be its own __slots__ plus the __slots__ of the parent class.
The __str__ and __repr____str__ () methods are used to specify what is printed on the print () object (to the user), and the __repr__ () method is used to specify what is directly printed (to the developer). When the content of the two is the same, you can directly assign a value to steal a lazy definition:
class Person (object): def __str__ (self): return ' str ' def __repr__ (self): return ' repr ' # __REPR __ = __str__p = Person () print (P) # strp# Repr
__iter__ and __next__ If a class wants to be used in a for...in loop, it must define a __iter__ () method that returns an iterative object that takes the next value of the loop through the __next__ () method of the Iteration object. Exits the loop until a stopiteration error is encountered. Take the Fibonacci sequence as an example:
Class Fib (object): def __init__ (self): self.a, self.b = 0, 1 def __iter__ (self): return self def __ Next__ (self): self.a, self.b = self.b, SELF.A + self.b if SELF.A >: raise Stopiteration () return SE Lf.afor N in Fib (): print (n) # # # 3# AA 8
__getitem__, __setitem__, and __delitem__ need to define __GETITEM__ (), __setitem__ (), and __delitem () __ methods to manipulate objects based on subscripts. The subscript behavior may be an int, a slice (slice type, possibly a step), or an object that can be a key, such as Str. So to implement these methods is not simple, you need to consider a variety of situations (list, tuple, dict) and a variety of usages (index, slice, key), here is not an example. __getattr__ normally, when a property or method of a class is called, an error (ATTRIBUTEERROR) occurs if it does not exist, and the __getattr__ () method can handle the problem. When the __getattr__ () method is defined, if a method or property does not exist, the __getattr__ (self, attr) method is called, and the second parameter is the method name, which can be handled on its own. With fully dynamic __getattr__, you can write a chain call:
def Chain (object): def __init__ (self, Path = "): Self._path = Path def __getattr__ (self, Path): return Chain ("%s/%s"% (self._path, path)) def __str__ (self): return self._path __repr__ = __str__chain (). status.user.timeline.list#/status/user/timeline/list
__call__ You can define the __call__ () method if you want to invoke it directly on the instance itself. The __call__ () method can also define parameters. The invocation of an instance is like a call to a function. So what if a variable is an object or a function? More often than not, we judge whether an object can be called, or by the callable () function. More customizable methods can be found in the official documentation.
8. Using enum class enum You can define related constants in a class, and class is immutable, and members can be compared directly.
from enum Import enummonth = enum (' Month ', (' Jan ', ' Feb ', ' Mar ')) for name, member in Month.__members__.items (): print ( Name, '--', member, ', ', Member.value) # Jan-Month.jan, Month.feb, # Month.mar, 3
The enumeration value is set to 1 by default. If you want to customize a value, you can derive the custom class from Enum:
From enum import enum, Unique@uniqueclass Weekday (enum): Sun = 0 Mon = 1 Tue = 2day1 = Weekday.monprint (day1) # Weekday.monprint (Weekday.mon) # weekday.monprint (weekday[' Mon ']# weekday.monprint (Weekday (1)) # Weekday.monprint ( Day1 = = Weekday.mon) # True
@unique adorners can help check for no duplicate values. There are multiple ways to access an enumeration type, either by referencing the enumeration constant with the member name, or by getting the enumeration constant directly from the value of values.
9. The biggest difference between using a meta-class dynamic language and a static language is that the definitions of functions and classes are not defined at compile time, but are created dynamically at run time. The type () function can look at a class or variable, the type of class, and the type of the instance is class. The type () function can either return the types of an object or create a new type.
DEF fn (self, name = ' World '): Passhello = Type (' Hello ', (object,), dict (hello = fn)) H = Hello () H.hello () print (Type (Hel Lo) # <class ' type ' >print (Type (h)) # <class ' __main__. Hello ' >
To create a Class object, type () passes through three arguments in turn: The name of the class, the inherited parent collection, and the class's method name and function binding. In addition to using type () to dynamically create a class, you can also use Metaclass to control the creation behavior of the class. Metaclass not understand, at present not understand, temporarily left two links, continue to understand in depth: http://www.liaoxuefeng.com/wiki/ 0014316089557264a6b348958f449949df42a6d3a2e542c000/0014319106919344c4ef8b1e04c48778bb45796e0335839000
http://blog.jobbole.com/21351/
The above English original: Http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python
Python Learning Notes-object-oriented programming