1. Definition and use of class
- Class: used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to each object in the collection. An object is an instance of a class.
- Class variable (class attribute): class variable is common in the whole instantiated object. Class variables are defined in the class and outside the function body. Class variables are usually not used as instance variables.
- Data members: class variables or instance variables are used to process data related to classes and their instance objects.
- Instance variable (instance attribute): the variable defined in the method, which only works on the class of the current instance.
- Method: a function defined in a class.
- Method override: if the method inherited from the parent class cannot meet the needs of the child class, it can be overridden. This process is called method override, also known as method override.
- Inheritance: that is, a derived class inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class object. For example, there is such a design: an object of Dog type derives from the Animal class, so Dog is also an Animal.
- Instantiation: create an instance of a class and a concrete object of the class.
- Object: an instance of a data structure defined by a class. The object consists of two data members (class variables and instance variables) and methods.
Class is a template. The template can contain multiple functions, which implement some functions. Object is an instance created according to the template, through which the functions in the class can be executed.
A typical class is defined and used as follows:
#Create class class Foo: #Class is the keyword and Foo is the class name class_int = 10 #Class variable #Create a function (method) in a class def bar(self,name): #self is a special parameter, which is required for instantiation of a class. print('bar') obj = Foo() #Create object obj based on Foo print('Class access class variables:',Foo.class_int) print('Object access class variables:', obj.class_int) obj.bar(3)
Output:
Class access class variables: 10 Object access class variables: 10 bar
Please note:
- Call class properties:
(1) accessing class variables in class: class name. Class variable name
(2) access class variables outside the class: class name, class variable name or instance name, class variable name - Call instance properties:
(1) accessing instance variables in class: self. Instance variable name
(2) access instance variables outside the class: instance name. Instance variable name - Call instance method:
(1) access instance method in class: self. Method name (parameter) or class name. Method name (self, parameter)
(2) out of class access instance method: instance name. Method name (parameter)
2. Three characteristics of objects
Like all object-oriented languages, python objects also have three characteristics: encapsulation, inheritance and polymorphism.
2.1 packaging
Encapsulation, as the name suggests, is to encapsulate the content somewhere, and then call the content encapsulated somewhere.
(1) Invoking encapsulated content through an object
The instantiated object is accessed by: object. Property name. The specific access forms are as follows:
class Foo: def __init__(self, name, age): self.name = name self.age = age obj = Foo('xiaoming', 22) print(obj.name,obj.age) print(type(obj))
Output:
xiaoming 22 <class '__main__.Foo'>
(2) Indirect access to encapsulated content through self
In fact, self is the instantiated object itself, so you can access the instantiated object through it.
class Foo: def info(self): print(self.name,self.age) def __init__(self, name, age): self.name = name self.age = age obj = Foo('xiaoming', 22) obj.info()
Output:
xiaoming 22
2.2 succession
As in real life, a subclass can inherit the content of the parent class. For example, first create an Animal class, and then cat and dog inherit it respectively.
class Animal: def eat(self): print("%s eat " % self.name) def drink(self): print("%s drink " % self.name) def shit(self): print("%s PULL " % self.name) def pee(self): print("%s Scatter " % self.name) class Cat(Animal): def __init__(self, name): self.name = name self.breed = 'cat' def cry(self): print('meow ') class Dog(Animal): def __init__(self, name): self.name = name self.breed = 'dog' def cry(self): print('Wang Wang barking') # ######### implement ######### c1 = Cat('Xiaoming's kitten') c1.eat() d1 = Dog('Xiao Hong's dog') d1.eat()
Xiaoming's kitten eats Xiaohong's dog eats
2.3 polymorphism
Polymorphism in python is not the same as polymorphism in parent and child classes in C + +. It needs to determine the direction of the method according to the specific direction of the object. The specific examples are as follows. Both S1 and S2 implement the show method. See its direction to decide which one to call.
class F1: pass class S1(F1): def show(self): print('S1.show') class S2(F1): def show(self): print('S2.show') def Func(obj): obj.show() s1_obj = S1() Func(s1_obj) s2_obj = S2() Func(s2_obj)
Output:
S1.show S2.show
3. Attribute (variable) binding
Python as a dynamic language, class objects and instance objects can bind any attribute at run time. Therefore, the binding of class properties occurs in two places, at the time of class definition and at any stage of operation.
3.1 class attribute binding
The following program introduces the class attribute binding methods in and outside the class, and the class attribute can also be deleted.
class Dog: kind = 'canine' #Class, class attribute binding Dog.country = 'China' # Class attribute binding print(Dog.kind, ' - ', Dog.country) # Output: canine - China del Dog.kind #Delete class properties print(Dog.kind, ' - ', Dog.country) # Class attribute is deleted. An error is reported!
Output:
canine - China Traceback (most recent call last): File "/home/liqiang/workspace/python/python_tutorials/main.py", line 8, in <module> print(Dog.kind, ' - ', Dog.country) # Class attribute is deleted. An error is reported! AttributeError: type object 'Dog' has no attribute 'kind'
3.2 instance attribute binding
Like class attribute binding, instance attribute binding also occurs in two places: at any stage of class definition and runtime.
class Dog: def __init__(self, name, age): self.name = name #Class, instance binding self.age = age dog = Dog('Lily', 3) dog.fur_color = 'red' # Class, instance property binding print('%s is %s years old, it has %s fur' % (dog.name, dog.age, dog.fur_color))
Output:
Lily is 3 years old, it has red fur
4. Attribute reference
4.1 class attribute reference
Class attributes are divided into two types: data attributes and method attributes. However, there is usually little need to reference class function attributes.
Data properties
class Dog: kind = 'canine' Dog.country = 'China' print(Dog.kind, ' - ', Dog.country) #Both are references to class data properties
Output:
canine - China
4.2 instance attribute reference
Instance objects can reference class properties and instance properties, and the rules are as follows:
- Find instance properties first, then class properties.
- When Binding attributes, new attributes are always created for the instance object (even if the same class attribute exists). When the attribute exists, only the object executed by the attribute is updated.
Code example 1:
class Dog: kind = 'canine' country = 'China' def __init__(self, name, age, country): self.name = name self.age = age self.country = country dog = Dog('Lily', 3, 'Britain') print(dog.name, dog.age, dog.kind, dog.country)
Output:
Lily 3 canine Britain
Note: both the class object dog and the instance object dog have the attribute country. According to the rules, dog.country will refer to the attribute of the instance object; However, the instance object dog does not have the attribute kind. According to the rules, the attribute of the class object will be referenced.
Code example 2:
class Dog: kind = 'canine' country = 'China' def __init__(self, name, age, country): self.name = name self.age = age self.country = country dog = Dog('Lily', 3, 'Britain') print(dog.name, dog.age, dog.kind, dog.country) print(dog.__dict__) dog.kind = 'feline' #Adding an instance property does not change the value of the class property print(dog.name, dog.age, dog.kind, dog.country) print(dog.__dict__) print(Dog.kind) #Class properties have not changed
Output:
Lily 3 canine Britain {'name': 'Lily', 'age': 3, 'country': 'Britain'} Lily 3 feline Britain {'name': 'Lily', 'age': 3, 'country': 'Britain', 'kind': 'feline'} canine
Note: using the new instance attribute outside the class will not affect the class attribute.
4.3 variable class attribute reference
In the following code, self.tricks.append(trick) is a variable class attribute reference, not an instance attribute!
class Dog: tricks = [] def __init__(self, name): self.name = name def add_trick(self, trick): self.tricks.append(trick) #Here is a variable class attribute reference, not an instance sub attribute d = Dog('Fido') e = Dog('Buddy') d.add_trick('roll over') e.add_trick('play dead') print(d.tricks)
Output:
['roll over', 'play dead']
If you want to use instance properties, you can define self.tricks first, and then append. As follows:
class Dog: tricks = [] def __init__(self, name): self.name = name def add_trick(self, trick): self.tricks = [] self.tricks.append(trick) #Here is a variable class attribute reference, not an instance sub attribute d = Dog('Fido') e = Dog('Buddy') d.add_trick('roll over') e.add_trick('play dead') print(d.tricks) print(e.tricks)
Output:
['roll over'] ['play dead']
4.4 an example illustrates class attributes, instance attributes and common variables
class TestClass(object): val1 = 100 def __init__(self): self.val2 = 200 def fcn(self, val=400): val3 = 300 self.val4 = val self.val5 = 500 if __name__ == '__main__': inst = TestClass() print(TestClass.val1) print(inst.val1) print(inst.val2) #print(inst.val3) # val3 is a local variable and an error is reported!!! #print(inst.val4) # val4 is not an instance attribute, an error is reported!!! #print(inst.val5)# val5 is not an instance attribute, an error is reported!!! print(inst.__dict__)
Output:
100 100 200 {'val2': 200}
It can be seen that inst has only one instance attribute, that is, val2.
- val1 is a class variable, which can be called directly by the class name or by an object;
- val2 is an instance variable that can be called by the object of the class. It can be seen here that the member variable must be given in the form of self. Because the meaning of self is to represent the instance object
- val3 is neither a class variable nor an instance variable. It is only a local variable inside the function fcn
- Neither val4 nor val5 are instance variables. Although they are given as self., they are not initialized in the constructor
5. Method
5.1 instance method, class method and static method
- Instance method: generally, the methods defined in the class are instance methods by default. The biggest feature of an instance method is that it must contain at least one self parameter, which must be defined, but it does not need to be passed when calling. Analogy to this pointer in C + +.
- Class methods: class methods need to contain at least one parameter (cls), but when calling class methods, there is no need to explicitly pass parameters for cls parameters. Class methods need to use the modifier statement: ï¼ classmethod. Class and instance objects can call class methods.
- Static method: similar to ordinary functions, except that it is defined in the class namespace, while functions are defined in the global namespace of the program. It has the following characteristics:
- Class static methods do not have special parameters such as self and cls;
- Class static methods cannot call the properties and methods of any class and object, and class static methods have little relationship with classes;
- Static methods need to be modified with ï¼ staticmethod;
- It can be called using a class or instance object.
- Class method example
class CLanguage: def __init__(self): self.name = "Xiao Ming" self.age = "22" # A class method is defined below @classmethod def info(cls): print("Calling class method", cls) # Class methods are called directly using the class name CLanguage.info() # Calling class methods using class objects clang = CLanguage() clang.info()
Output:
Calling class method <class '__main__.CLanguage'> Calling class method <class '__main__.CLanguage'>
- Static method example
class CLanguage: @staticmethod def info(name, age): print(name, age) # Call static methods directly using the class name CLanguage.info("xiaoming", "22") # Calling static methods using class objects clang = CLanguage() clang.info("xiaohong", "23")
Output:
xiaoming 22 xiaohong 23
5.2 calling other methods in case method
You need to add slef when calling the instance method internally.
class Dog(): def __init__(self, name, age): self.name = name self.age = age def get_dog_information(self): dog_information = "name is {0},age is {1}".format(self.name, self.age) return dog_information def get_dog_speak(self, love): dog_speak = self.get_dog_information() + love #Internal call instance method return dog_speak dog = Dog("jake", 13) print(dog.get_dog_speak("swimming"))
Output:
name is jake,age is 13swimming