Also say Python's class--based on python3.5

Source: Internet
Author: User

In object-oriented language, in addition to methods, objects, the rest of the focus is the class, in terms of meaning, the class is to have the same behavior object Induction. When one or more objects have the same properties, methods, and other common characteristics, we can generalize it into the same class. In terms of use, the existence of classes is to facilitate the management of Objects. The code for defining a class in Python is as Follows: class Simple_class (object):

#定义一个名为Simple_class的类, Python3 The default object as the base class for the class, where the difference between the new and the old class is not discussed here height = 1.58# defines a class variable def __init__ (self,name,age,): #重写 Initialization of the class,
#使其在初始化的时候需要传入name, Age two Parameters. Self is the default parameter for the class method Self.name = name #定义两个对象变量 Self.age = Age def print_details (self): #定义一个名为Print_details的对象方法 Print ("print_details method call: name is%s,age is%d"% (self.name,self.age)) Print ("uninitialized Access class variable: height =", simple_class.heigh T) # Access class variable Try:print (simple_class.name) #访问实例变量 because of an error, for program code execution gives an exception handling except Attributeerror as Error:print ("uninitialized Ask the exception information for the instance variable: ", error" obj = simple_class ("object", "#生成一个类的实例对象obj"). height = 1.88print ("class variable assigned to the instance after initialization height =", Obj.height) print ("original class variable after initialization: height =", simple_class.height) print ("access instance variable after initialization: name is", Obj.name) #访问实例变量obj. Print_details () #调用对象方法 #/////output results are as follows////////library/frameworks/python.framework/versions/3.5/bin/python3.5/users /penglong/documents/python/s10/day4/blog.py uninitialized Access class variable: height = 1.58 exception information for accessing an instance variable before initialization: type object ' Simple_class ' has No attribute ' name ' after initialization class variable assigned to instance height = 1.88 Primitive class variable after initialization: height = 1.58 After initialization Access instance Variable: name is Objectprint_details method Call: Nam E is Object,age is 115

above, we define a class that includes an overriding initialization method, a common class Method. A class variable, two instance Variable. From the output content, we analyze the difference between the class variable and the instance variable, before instantiating the object, you can directly access the class variable and take out the assignment to other variables, and the instance variable is after the instantiation, only through the instance object access variables, if there is a specific instance object directly through the class to access, The program will Error. This is the difference between the Two. In terms of usage, the individual thinks that a class variable is more like the default variable for an instance, and that he is the default variable with a value for each instance object that can be modified after instantiating the object without affecting other instance Objects. The instance variable is a unique variable for each instance and must be assigned before it can be used. Besides the initialization method and the method we define, the initialization method belongs to the class method and can be called directly. The object method needs to be called through an instance.

About Inheritance:

In the previous section of the code there is a concept about the base class, which is actually inheritance. When writing code, we want to do some extra expansion of a class without affecting its own state, that can write a subclass to satisfy, here first from the Single-weight inheritance, the code is as Follows:

Class Father_class (object):
#定义一个名为father_class的类, He is both the parent of the subclass and the base class for subclasses of subclasses name = "parent class" #定义一个类变量 def log (self):
#定义一个log方法 output the class name, which is not self.__class, so that when the subclass is called, Self will point to the subclass itself, which is inconvenient for log Resolution. print ("father_class") def public_func (self): #定义一个public_func方法, Output This method whether the quilt class has modified the print ("unmodified") class Son_ Class (father_class): #定义一个子类, directly inherits the parent class son_name = "subclass" #定义一个类变量 def son_log (self): #定义自身的log Print ("son_ Class ") def public_func (self): #修改父类提供的公共方法 Print (" Subclass Modify Parent Method ") class Grandson_class (son_class):
#定义一个名为grandson_class的类继承自son_class由于son_calss也是别人的子类
#所以son_class的父类是本类的基类 Grandson_name = Subclass of Subclass def grandson_log (self): #定义自身log Print ("grandson_ Class ") def public_func (self): #对基类方法进行修改 Print (" Subclass Modify base class method ")
####### #父类的实例对象 ######### #father = father_class () #生成一个父类的实例对象name = father.name
#获取类变量的值并打印, The class variable itself can be obtained without instantiation, but the following requires an instance invocation method, so Mr. Print ("parent class accesses itself class variable:", Name) father.log () #父类调用自身的方法father. public_ Func () ###### #子类的实例对象 ########## #son = son_class () #实例化一个子类对象name = Son.name #子类去获取父类的类变量并这打印. The output is correct, stating that subclasses can inherit all class variables from the parent class.
#同理也可以继承父类所有实例变量, The code is not an example, but the same principle as print ("subclass Access parent class variable:", Name) son.log () #子类调用父类的方法, The output is correct, the child class can inherit all the methods of the parent class name = Son.son_name #子类访问自身类变量的值并打印, The result is unmistakable, stating that subclasses can add the class variable print ("subclass access to its own class variable:", Name) #son. son_log () #子类调用自己的log方法, stating that subclasses can augment their own methods Son.public_ Func () #子类调用父类的方法, But the output is different because we have modified it in the subclass to show that subclasses can modify the parent class method ######## #子类的子类的实例对象grandson = Grandson_class () # An instance object that generates a subclass of a subclass name = grandson.name# Subclass directly accesses the class variable of the parent Class's parent class and prints it,
#结果无误, We also inherit the parent class of all parent classes, chain-like, except that we inherit the variables of the parent class. Print ("subclass access base class variable:", Name) Grandson.log () #子类调用父类的父类的方法, similarly, subclasses inherit all methods of the parent class Grandson.public_func () # Subclasses can directly modify the parent Class's method ####### #输出结果如下 ############## #父类访问自身类变量: The parent class Father_class not modify the subclass to access the parent class Variable: parent class Father_class subclass accesses its own class variable : Subclass Son_class Subclass Modify Parent class method subclass Access base class Variable: parent class Father_class Subclass Modify base class method

 

The above code is a simple single-inheritance generalization, and from the code, you can see that when a class inherits from another class, it will have all the data of the parent class, including the parent class variable, the parent Class's instance variable, and the parent class method, which includes the class method and the instance Method. At the same time, the role of a subclass is to augment the parent class, which means that it can increase and change all the data of the parent class. Python is a multi-inheritance language, sometimes we want to have two classes at the same time, that directly inherit two classes Can. The simple construction code is as Follows:

Class A (object):    def a (self):        passclass b (object):    def b (self):        passclass c (a, b):    passc_test = C ( ) c_test.a () c_test.b ()

As can be seen from the above code, the C class inherits from a a, a, two class, so it can call both A's method and the method of B. (ios can only be implemented by Protocol: Bad reviews!!! , multiple inheritance is almost the same as single inheritance, but it is worth noting that multiple inheritance involves method Duplication. well, Here's a Question. Ordinary inheritance and Super Inheritance. First look at a piece of code:

Class A (object): #这么简单的代码. I won't explain.    def __init__ (self):        print ("A") class B (object):    def __init__ (self):        print ("B") class C (A):    def __init__ (self):        print ("C")        a.__init__ (self) class D (A):    def __init__ (self):        print ("D")        a.__init__ (self) class E (b,c):    def __init__ (self):        print ("E")        b.__init__ (self)        c.__init_ _ (self) class F (d,e):    def __init__ (self):        print ("F")        e.__init__ (self)        d.__init__ (self) a = E () Print ("---------") b = F () ##### #看一下输出记录, in order to save the land, I synthesized two lines of ######### initialization class E resulting in the output e B C a#---------# initialize F class The resulting output F E b c a D a

  

Analyze the above code, a, B directly inherit from the base class, each has its own initialization method, at the time of initialization to output its own class Name. C,d all inherit from a, overwriting their initialization method, so that they not only output their class name at initialization time, but also invoke the initialization method of their parent class to output their parent class name at the same time. E,f Two classes are multiple inheritance. To see the result of initializing class e, no exception, It initializes itself, invokes the initialization method of the parent class, and invokes the initialization method of the parent Class's parent class. Let's look at the initialization results of class F. Here's the Problem. It outputs two A. The result can be Analyzed. It calls the two Class A initialization method, which is extremely reluctant to see in the Code. Let's analyze the code to see how the problem Occurs. First F inherits from D,e two Classes. and D inherits from A,e inherits from B,c. Further analysis, B inherits from the base class. and C inherits from A. The problem here is that each inherited a class, and we have initialized the method call to it. That is, in F we call two times A's initialization method, so the output is two Times. In practical use, we will also encounter this Problem. That is, in multiple inheritance, it is often because of the complexity of the class that some parent methods are called repeatedly by their subclasses or subclasses of their subclasses or Subclasses. so, we need to use a keyword super to solve this problem, the code is as Follows:

Class A (object): #代码都差不多. This does not explain.    def __init__ (self):        print ("A")        Super (a,self). __init__ () class B (object):    def __init__ (self):        Print ("b")        Super (b, self). __init__ () class C (A):    def __init__ (self):        print ("c")        Super (c, self). __ init__ () class D (A):    def __init__ (self):        print ("d")        super (d, self). __init__ () class E (b,c):    def __ init__ (self):        print ("e")        super (e, self). __init__ () class F (d,e):    def __init__ (self):        print ("F" )        Super (F, self). __init__ () a = E () print ("---------") b = F () ##### #看一下输出记录, in order to save the land, I synthesized two lines of ######### initialization class E output e b C a#---------# initialize F class resulting output F D E B C A

As above, compared to two code, it is not difficult to see the role of super, first it automatically find the parent class initialization method and call, while guaranteeing only be called once, and strictly follow the class inheritance route, about the last point can compare two times the output order of the code, This sequence involves Python's multi-inheritance sequential algorithm, forget it. In addition to the initialization method, for other methods, super has the same effect, it should be noted that super only for the new class. In single inheritance, super is probably used to lazy-expand the Parent-class construction method. But! Mixing super classes and common inheritance classes is dangerous, so single-inheritance individuals are seldom used.

above, the question of inheritance basically finished, finally say the decorator in the class method of the use of code as Follows:

Class Test (object): #定义一个类. Don't give a name.    name = "test" #类变量    def __init__ (self,age): #初始方法, pass parameters        Self.age = age# Define an instance variable, assign the passed in parameter directly to it    def say (self): # normal method without adorner, output a test,ps: after only instantiating through instance call        print ("test")    @staticmethod # plus Adorner @staticmethod method,    def say2 ():        print ("say hi 2") #即静态方法 No need to instantiate the call, the parameter cannot be Passed. When a class has only static methods, in a sense it is simply a class toolkit    @classmethod    def say3 (self):        print ("say Hi 3") # class method, which does not need to be instantiated to invoke, can use class parameters , cannot use instance parameters, there are no arguments to do this example: I'm sorry.    @property #加 @property method    def say4 (self):         # print ("this is 4")         return  "test" #可以返回数据, In the sense of use, it is to pass the data that is processed by the class Method.

These are some simple considerations for classes in python, and as a major focus of object-oriented, the concept of class has a lot to dig into. For example, parameter types and so on, these need to slowly explore Themselves.

Also say Python's class--based on python3.5

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.