1. Object oriented

A class is a collection of objects that have the same properties and methods.

Class variables: Class variables are common throughout the instantiated object. Generally defined in a class and outside the function body.

Method: a function in a class

Data members: Class variables or instance variables are used to process data related to a class and its instance objects.

Method override: If a method inherited from a parent class does not meet the needs of a subclass, it can be overridden. This process is called method override, also known as method rewriting.

Local variables: Variables defined in a method that apply only to the class of the current instance.

Instance variables: In the declaration of a class, properties are represented by variables called instance variables, which are a variable decorated with self.

Inheritance: A derived class inherits the fields and methods of the base class. Inheritance also allows an object of a derived class to be treated as a base class object. Just like we defined a fruit class, and then we defined a fruit class derived from apple, and it had some properties and methods of the Fruit class, and it had some unique properties and methods of its own, and it had an ‘IS-A’ relationship with the fruit class.

Instantiation: A concrete object of a class. a class is like a template that can only be manipulated by instantiating it as an object.

Object: Instance of a data structure defined by a class. An object consists of two data members (class variables and instance variables) and methods.


Class definition

Define a class:

class ClassName:.... . .Copy the code

It is recommended that class names be humped or all uppercase letters


3. Use class object methods

Class objects support two types of operations: attribute reference and instantiation

Attribute references: As with other syntax in Python, obj.name

Attributes with __ in a class are private attributes of the class. Private attributes, like __name, are not directly accessible outside the class.

Self. number = 100 def get_number(self): a = self.number + 100 return aCopy the code


f = Fruit()print('We have {0} fruits'.format(f.number))print('We have {0} fruits'.format(f.get_number()))
Copy the code

Output result:

We have 100 fruitsWe have 200 fruits
Copy the code

4. Construction method

Python classes have a special method called __init__(), called a constructor. This method is called automatically when the class is instantiated (it can be used to initialize class attributes, etc.), similar to the class constructor in C++.

def __init__(self):self.data = []
Copy the code

A class defines an __init__() method, which is automatically called by instantiation of the class.

 

Class Fruit:def __init__(self): print(' you have instantiated an object ') f = Fruit()Copy the code

The output

You've instantiated an objectCopy the code

The init_() method can have arguments that are passed to the class’s instantiation by init().

class Complex:def __init__(self,real,image):self.r = realself.i = imagedef get_complex(self): Print ('complex real is %.2f, image is %.2f'%(self.r,self.i)) a = complex(3.5, -1) a.goet_complex ()Copy the code

 

The following output is displayed:

Complex real is 3.50, image is -3.00Copy the code

Self represents an instance of the class, not the class. Class methods differ from ordinary functions in only one special way — they must have an extra first argument name, which by convention is self. But self is not a Python keyword.

 

Self stands for the address of an object after you instantiate it from a class. Much like the C++ class class Test pointer:

def prt(self):        print(self)        print(self.__class__)
t = Test()t.prt()
Copy the code

Output:

 

<__main__.Test object at 0x0000025EC6D45608><class '__main__.Test'>
Copy the code

Class methods

Inside a class, the def keyword is used to define a method. Unlike normal function definitions, the class method must contain the argument self as the first argument. If you don’t need to pass self as an argument, you need to prefix the function with @staticmethod, which represents a staticmethod

​​​​​​​

class Complex:def __init__(self, real=None, image=None):self.r = realself.i = image def get_complex(self): print('complex real is %.2f , image is %.2f' % (self.r, self.i)) @staticmethoddef test(a, b): Print ('complex real is %.2f, image is %.2f' % (a, b)) a = complex(3.5, -3) a.goet_complex ()b = complex() b.test(3, -2)Copy the code

The output

Complex real is 3.00, image is-3.00 Complex real is 3.00, image is-3.00Copy the code

6, inheritance,

Python also supports class inheritance in the following format:

class Derivedclassname(Baseclassname): ... .Copy the code

Baseclassname must be defined in the same scope as the derived class. In addition to classes, expressions can be used, which is useful when the base class is defined in another module:

class Fruit: def __init__(self,sweet): self.sweetness = sweet def describe(self): Print ('Our fruit has a daily value of %.2f'%self. daily value) class Apple(fruit): Fruit class def __init__(self,sweet,color): Self. color = color Fruit.__init__(self,sweet) def describe(self) {0:. 2 f} %, and color is {1} '. The format (self. Sweetness, the self color)) = apple apple (62.2, "red") apple. The describe ()Copy the code

Output:

 

Our apple has a constant value of 62.20%,and the color is redCopy the code

 

Multiple inheritance

Python can also inherit from multiple base classes:

class Derivedclassname(basename1,basename2,...) :... . .Copy the code

Notice the order of the parent classes in parentheses. If the parent class has the same method name that is not specified when the child class is used, Python searches from left to right. That is, if the method is not found in the child class, python searches from left to right to see if the parent class contains a method.

class Fruit: def __init__(self, sweet): self.sweetness = sweet def describe(self): print('Our fruit has a sweetness of %.2f' % self.sweetness) class Food: def __init__(self, uprice, num): self.unit_price = uprice self.number = num self.total_price = num * uprice def cost(self): print('You need to pay {0:.3} yuan, thank you'.format(self.total_price)) class Apple(Fruit, Food): def __init__(self, sweet, color, uprice, num): self.color = color Fruit.__init__(self, sweet) Food.__init__(self, uprice, num) def describe(self): print('Our fruit has a sweetness of {0:.2f}%,and color is {1}'.format(self.sweetness, Self. Color)) = apple apple (62.2, "red", 3.5, 21) apple. The describe () apple. The cost ()Copy the code

Output:

 

Our fruit has a insic value of 62.20%,and color is redYou need to pay 73.5 yuan, thank youCopy the code

7. Method rewrite

If the functionality of the parent method does not meet your needs, you can override the parent method in the subclass. If you want to call the overridden base method, you can use super(subclass name, subclass instance object name). The parent class method

Class Parent_class: def Method(self): print (' Parent_class ') class Child_class(Parent_class): Print (' subclass Method ') c = Child_class() # subclass instantiate c.method () # subclass call override Method super(Child_class,c).method () # call Method whose parent class has been overridden by the subclass objectCopy the code

A subclass inherits the superclass constructor

If you need the parent constructor in a subclass, either explicitly call the parent constructor or do not override the parent constructor.

  •  
class A:    def __init__(self, x, y):        self.x = x        self.y = y        print('pos is ({0},{1})'.format(self.x, self.y))
    def xxx(self):        print('parent now')

class B(A):     def xxx(self):        print('child now')

b = B(10, 3)b.xxx()
Copy the code

The output

  •  
Pos is child now (10, 3)Copy the code

 

If __init__ is overridden, the child class is instantiated, and __init__ defined by the parent class is not called.

If __init__ is overridden, to inherit the parent constructor, use the super keyword super(subclass, self).__init__(argument 1, argument 2,….). , or the name of the parent class.__init__(self, argument 1, argument 2…)


Class private attributes

Starting with two underscores, declare that the property is private, like __name that cannot be used or accessed directly outside the class. Self.__name when used in a method inside a class.

 

Class JustCounter: __secretCount = 0 # publicCount = 0 # publicCount (self): self.__secretCount += 1 self.publicCount += 1 print(self.__secretCount) counter = Count ()counter. Count ()print(counter. PublicCount)print(counterCopy the code
Traceback (most recent call last):File "test.py", line 16, in <module> print (counter.__secretCount) Instance cannot access private variable AttributeError: 'JustCounter' object has no attribute '__secretCount'Copy the code

 

Starting with two underscores, declare that the method is private, like _private_method, and can only be called inside the class, not outside it. Self. __private_method.

 

class Site: def __init__(self, name, url): self.name = name # public self.__url = url # private def who(self): Print ('name: ', self.name) print('url: ', self.__url) def foo(self): Print # public method (' this is a public methods) self. __foo (x) = Site (' * * * ', 'www.xxx.com') x.w ho (#) normal output x.f oo (#) normal output x. __foo () # errorCopy the code

Output:

Name: ***url: WWW.***.com File "F:\Python\Program\test.py", line 61, in <module> x.__foo() # AttributeError: 'Site' object has no attribute '__foo''''Copy the code

 

Class

__init__ : constructor, called when an object is generated, similar to the C++ constructor

__del__: destructor used to free objects, similar to the C++ destructor used to free requested memory

__repr__: Print, convert. This function controls the string output by the class as it prints

 

class Name:    def __init__(self, name):        self.name = name

print(Name('s'))
Copy the code

 

'''<__main__.Name object at 0x0000023744AFD248>'''
Copy the code
Class Name: def __init__(self, Name): self. Name = Name def __repr__(self): # r})'.format(self.name) print(Name('s')) '''Name('s')'''Copy the code

 

 

__setitem__ : This method is called whenever an attribute is assigned, so no self.name = value can be assigned to this method in an infinite loop

__getitem__: This method is called when accessing nonexistent properties

__len__: Get the length. If a class behaves like a list, len() is used to get the number of elements. For len() to work properly, the class must provide a special method __len__(), which returns the number of elements.

class CountList:    def __init__(self, *args):        self.list = [x for x in args]        self.count = self.__len__()
     def __len__(self):         return len(self.list)
     def get_count(self):         return self.count

a = CountList(1, 2, 3, 4, 4, 5)print(a.get_count())print(len(a))​​​​​​​
Copy the code

__cmp__: comparison operation

__call__: function call

__add__ : add operation

__sub__ : subtraction operation

Class MyClass: def __init__(self, height, weight): self.height = height self.weight = weight # Return a new class def __add__(self, others): Return MyClass(self.height + others.height, self.weight + others.weight) # Return a new class def __sub__(self, others): Return MyClass(self.height-others. height, self.weight-others. weight) def intro(self): Def main(): print(" height = ", self.weight = ", self.weight) def main(): a = MyClass(height=10, weight=5) a.intro() b = MyClass(height=20, weight=10) b.intro() c = b - a c.intro() d = a + b d.intro() if __name__ == '__main__': main()Copy the code
  •  
High: 10:5 High: 20:10 High: 10:5 High: 30:15"Copy the code

__mul__ : by operation

__truediv__ : divide

__mod__: Complements operations

__pow__ : power

The same. The class’s proprietary methods can also be overridden