python class study notes

A key concept of Object Oriented Programming (OOP) is to encapsulate data and operations on data to form an interdependent and indivisible whole , namely Object. After abstracting the objects of the same type, the common characteristics are obtained to form the class Class.
The list of built-in data types, dictionaries, tuples, etc. are all classes. To learn Python, you must be familiar with classes. Starting from related concepts, we will sort out classes.

1 Properties and methods

Class is to put together the data and the operation methods on the data. The data is nothing more than variables, and the operation methods on the data are nothing more than functions. These two are collectively called class members; while functions are called member methods , and variables are called member properties .

2 instance attributes and class attributes

Member attributes are divided into instance attributes and class attributes,

  • Instance attributes generally refer to those defined in the constructor __init__, and must be prefixed with self when defining and using it
  • Class attributes are variables defined outside of all methods in the class. The
    instance attributes are determined by the instance. Different instances can be different instance attributes; while the class attributes are global, and the class attributes of each instance are the same; (instance attributes The relationship with class attributes is like the relationship between local variables and global variables)
class Car: 
    price = 10000  # 这是类属性, 定义在所有方法之外
    def __init__(self, c): 
        self.color = c   # 这是实例属性 

Since class attributes are global, they can be accessed through class, attributes and instance attributes, while instance attributes can only be accessed through instance attributes.

car1 = Car('red') #创建一个对象, 也叫做类的实例化 ,从人类 到具体的 “张三”
Car.price  #类.属性访问
>>>10000
car1.price  #实例.属性访问
>>>10000
Car.color 
>>>AttributeError: type object 'Car' has no attribute 'color' # 实例属性不可以通过 类.属性 访问
car1.color
>>>'red'
isinstance(car1, Car)  #  查看一个对象是否为某个类的实例
>>> True

After the class definition is completed, python can dynamically add or modify members, as follows

Car.company = "Volkswagen"  # 增加成员属性 
Car.price = 11111  # 修改成员属性 
def setSpeed(self, s): 
    self.speed = s 
import  types 
Car.setSpeed  = types.MethodType(setSpeed, car1) # 增加成员方法  

The difference between a method and a function is that a method generally refers to a function related to an instance. When calling a method, the instance itself will be passed as the first parameter. Therefore, when adding a member method, you must call types.MethodType() to convert the function into a method. Then it can be added to the class.

Attributes

Attributes and methods are variables, and the other is a function. When called, there is a parenthesis. The method can also be attributed, and it can be called without parentheses.

class Car: 
    price = 10000  
    def __init__(self, c): 
        self.color = c   
    def showcolor1(self):
        return self.color
        
    @property    # 属性装饰器
    def showcolor2(self):
        return self.color
car = Car('red')
car.price   # 访问属性
>>>10000
car.showcolor1() # 调用方法 
>>>'red'
car.showcolor2   # 方法属性化 
>>>'red'

dir(class_name) view methods and attributes in the class, help(class.method) view method descriptions

dir(car) 
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'color',
 'price',
 'showcolor1',
 'showcolor2']

3 Public and private members

For data confidentiality, some variables need to be set as private attributes, so that methods cannot be directly accessed from outside the class, that is, private members; the opposite is public members.

  • __x, the ones beginning with double underscores in python are private members
  • _x, a single underscore at the beginning is a protected member, it cannot be imported using import, only within the class or subclasses can be used
  • x , the ones with underscores on both sides are special members.
class Car: 
    __price = 10000  
    def __init__(self, c): 
        self.color = c  
car = Car('red')
Car.__price
AttributeError: type object 'Car' has no attribute '__price'
car.__price
AttributeError: type object 'Car' has no attribute '__price'  # 不管是实例还是类都不能访问私有成员

But for program testing and debugging, python provides a way to access private members outside the class, "instance._class__private attributes"

car = Car('red')  
car._Car__price
>>>10000   # 可以访问 

4 Public methods, private methods, static methods, class methods

Both public and private methods belong to instances (the first parameter is self), each instance has its own public and private methods, but private methods cannot be called directly through the instance. Private methods can only be called internally (or Called through a special way of python).

class Car: 
    def __init__(self, c): 
        self.color = c 
    def __show(self):    #  私有方法 
        print(self.color)
    def setColor(self, newcolor):  # 公有方法 
        self.color = newcolor 
        self.__show()
car1 = Car('red') 
car1.__show()
>>>AttributeError: 'Car' object has no attribute '__show'
car1.setColor("bule")
>>>bule

You can see that for the private method __show(), it is hidden for you when it is called from the outside, to lie to you, but the public method setColor() inside the class can be called through self.__show().
Static methods and class methods can be called by class name and instance name, but they cannot directly access instance members, only class members. They are all general methods.

class Car: 
    price = 10000
    def __init__(self, c): 
        self.color = c   # 这是实例属性 
    @classmethod   #类方法修饰器
    def showprice(cls): 
        print(cls.price)
    @staticmethod  # 静态方法修饰器
    def sayhello(): 
        print('hello')   
car1 = Car('red') 
car1.showprice()
car1.sayhello()
>>>10000
>>>hello

Note: Class methods and static methods are not dependent on the instance, and cannot call instance members

Operator overloading

Why does the addition of the int class and the addition of the list have the same sign "+", but the operation method is different, this is the overload of the operator, for the same operator, the calculation method defined for different classes.
For example, for the Car class, define two cars "+" as the sum of their prices, and overload __add__

class Car: 
    def __init__(self, color, money): 
        self.color = color
        self.money = money
    def __add__(self, anothercar):
        if isinstance(anothercar, Car): 
            return self.money + anothercar.money
        else : print('this is nor a car ')
car1 = Car("red", 10000)
car2 = Car("bule",10000)
car1 + car2
>>>20000

inherit

Inheritance is designed for reuse. When a new class is needed, if the new class is a subclass of a designed class, then it is a smart and efficient method to directly call the designed class, which are called subclasses and subclasses. father. This behavior is inheritance.
For example, now we need a Volkswagen class that can inherit the functions of the Car class.

class Volkswagen(Car): 
    def setmodel(self, m): 
        self.model = m 
car3 = Volkswagen( 'yellow', 100)
car3.color
>>>'yellow'
car3.money
>>>100    # 继承了负类的成员 
car3.setmodel('迈腾')
>>>car3.model 
'迈腾'

To view the subcategories of a class, you can use issubclass(son, father). or class.__bases__ to view the parent category.

issubclass(Volkswagen, Car) 
True

Volkswagen.__bases__
(__main__.Car,)

Content reference:
python programming, Dong Fuguo, Tsinghua University Press
Participating in the bird tutorial Python object-oriented

Guess you like

Origin blog.csdn.net/weixin_43705953/article/details/109334770