First, create category
class Animal: DEF setName (Self, name): self.name = name DEF getName (Self): return self.name # create an object animal cat cat = Animal () cat.setName ( " cat " ) # call the cat object attribute name Print (cat.name) # call the cat method getName method Print (cat.getName ()) # call the cat method getName method another way Print (Animal.getName (cat))
- Create a custom class using the keyword class, the class name follows the class
- A method is a function of the class
- Each method first argument is self, if there are multiple parameter method, the first argument will be used as self argument, when calling the method, do not have to pass this parameter, the system will be the object method belongs this parameter is passed.
- There are two ways to call an object method, an object is through a direct call; the other is by calling the class and pass the corresponding object.
Privatization Second, the method of
In the Java language provides such a private key, the privatization method or variable, but does not provide in python, but you can use other ways to achieve this effect, in front of the python class method name with "__ "external access method can eliminate this class.
class FOO: DEF f1 (Self): return " I f1 " DEF __f2 (Self): return " I'm F2 " # inner classes can call private methods DEF F3 (Self): return . Self __f2 () f = FOO () an 1 () F. __f2 () # AttributeError: 'FOO' Object attribute has NO '__f2'
F2 is a private method can be seen, can not be accessed outside the class, otherwise it will throw an exception, but within the class can call the private methods.
f2 whether it is really in a class can not call outside of it? Of course not, in fact, python compiler encounters "__" at the beginning of the method method name will become "_ClassName__MethodName", shining calls this form is feasible.
... Print (f._FOO__f2 ()) # I F2 ...
In addition, if you want to see all of the methods in the class, how?
import inspect methods=inspect.getmembers(f,predicate=inspect.ismethod) print(methods)#[('_FOO__f2', <bound method FOO.__f2 of <__main__.FOO object at 0x0000000000676F28>>), #('f1', <bound method FOO.f1 of <__main__.FOO object at 0x0000000000676F28>>), #('f3', <bound method FOO.f3 of <__main__.FOO object at 0x0000000000676F28>>)]
Third, the class inheritance
Inheritance class is a class to get all the members from another class, the members of the parent class can be used in a subclass. The new class can inherit one or more parent classes (python support multiple inheritance), the parent class can be called a base class or super class, the new class is called the derived class or subclass.
class A: Pass class B: Pass class C (A): # single inheritance and C is a derived class, A is the base class Pass class D (A, B): # multiple inheritance, multiple inheritance class, separated by commas apart pass
A class D class will inherit the order from left to right, a member of class B, if a plurality of the same parent class members, the parent class will inherit the order written, that is to say in front of the parent class overrides written on the back of the same name as the parent class method.
Fourth, the detection inheritance
Sometimes necessary to determine whether the inheritance relationship between classes, this method can be used in the parent class, then this inheritance should be how to judge it? Issubclass determination function may be used, it receives two parameters, a first subclass, the second is the parent class, if inheritance return True, otherwise returns False, indirect inheritance are also suitable.
class Fruits: pass class Apple(Fruits): pass print(issubclass(Apple,Fruits))#True
If you get a parent who is known class of class, you can directly use the "__bases__", which is a kind of special property
class Fruits: pass class Apple(Fruits): pass print(Apple.__bases__)#(<class '__main__.Fruits'>,)
Five classes, class members, subject to determination
a, hasattr ()
Determine whether there is an object or class members
class Bar: def f1(self): pass b=Bar() print(hasattr(b,"f1"))#True print(hasattr(Bar,"f1"))#True
b、getattr()
Gets the value of an object or class of members, it has three parameters used to develop the third parameter default values
class Bar: def f1(self): pass b=Bar() print(getattr(Bar,"f1"))#<function Bar.f1 at 0x0000000000535BF8>
c、setattr()
Value used to set the object members, setattr function has three parameters, the first two getattr the same value for the third parameter specified member
# If the object has a name attribute, the value is updated, if not, adds a new attribute name, can update or add class attributes setattr (B, " name " , " Bright " ) Print (b.name) # bright
Dynamically add function
class Bar: DEF F1 (Self): Pass B = Bar () # ### was added f2 function class #### DEF f2 (): Print ( " dynamic additive f2 " ) setattr (Bar, ' f2 ' , f2) Bar.f2 () # class calls # ### function f2 object is added ### DEF f2 (): Print ( " dynamic additive f2 " ) setattr (B, ' f2 ' , f2) b.f2 () # object invokes
d、isinstance
Determining a relationship between classes and instances
class A: print("A") class B(A): print("B") a=A() b=B() print(isinstance(a,A))#True print(isinstance(b,A))#True
Six polymorphic
Objects of the same variety of forms, polymorphic increase the flexibility of the program, and scalability.
Polymorphism implementation steps:
- Define a new subclass
- Method override the corresponding parent
- Subclass method to deal directly, do not call the parent class method
class Animal: def eat(self): pass def run(self): pass class Dog(Animal): def run(self): pass
Simply put, Dog is newly defined subclass, do not want to call the run method of the parent class needs to implement their own run method, which is polymorphic, multiple objects generated by a class, call the same method, produce different execution result.