[Python] classes and objects

 

table of Contents

Object-Oriented Programming

Encapsulation (information shielding)

Inheritance (the way that child classes automatically share the parent class)

Polymorphism

Class-related knowledge

self

Construction and destruction

__init__(self, param1, param2...)

__new__(cls, ...) [rarely used]

Private variable

inherit

Python supports multiple inheritance

combination

Class definition, class object and instance object

Bind

Destroy class del

Class-related built-in methods

issubclass(classA, classB)

isinstance(obj, class)

hasattr(object, name)

getattr(obj, name [, default])

setattr(obj, name, value)

delattr(obj, name)

property(fget=None, fset=None, fdel=None, doc=None)

to sum up


Object=attribute+method

class Student:
    #属性
    color = 'green'
    weight = 10
    legs = 2
    shell = True
    mouth = '小嘴'

    #方法
    def climb(self):
        print('爬?')
    def run(self):
        print('跑a a a a a ')
    def walk(self):
        print('优雅~')

Object-Oriented Programming

Encapsulation (information shielding)

Inheritance (the way that child classes automatically share the parent class)

Polymorphism

Little turtle teacher understands polymorphism in a deeper level. Both classes A and B in Shangli have no parent class, but it can be assumed that there is a parent class, and the parent class has a fun method, and classes A and B respectively overload the fun method, thereby expressing The same parent class and the same method have different results, and this is polymorphism. Polymorphism can actually be understood as that tigers, birds, and monkeys are all creatures (inherited from the same parent class named "creatures"), and creatures have a survival skill "escape" method, but tigers, birds, and monkeys are each The escape method is different. These cases of [same parent class, same method signature, but different actual effects of the method] are polymorphic. Suppose you, as an observer of the universe, saw tigers, birds, and monkeys running away at the same time, but their escape forms were different, and exclaimed: "It runs so fast, and each one is different~"

Class-related knowledge

self

Self is equivalent to the this pointer (the current context object). The first parameter of each method is fixed to self. When the method is called, the first parameter self is passed to the method itself by default, and the second parameter is passed directly to the method itself.

Construction and destruction

__init__(self, param1, param2...)

Initialization method

The __init__ method must return None, otherwise an error will be reported

__new__(cls, ...) [rarely used]

Construction method? __new__ is executed before __init__, it needs to pass in a cls object (an object obtained after the space is opened up by memory) and related required parameters. For example, the following str class requires string parameters to be passed in

The upper chestnut belongs to the inherited immutable type str, but the content needs to be modified in advance . Specifically, it first inherits the str class, then rewrites __new__, first converts the incoming string to uppercase, and then continues to execute the __new__ method of the str class and returns its return value.

 

Private variable

__name is a private variable, the variable name prefix is ​​double underscore'__', all are private variables, otherwise public variables (ps: private methods can be operated by public methods)

You can use _class name__ variable name to access, for example:

inherit

import random as r

class Fish:
    def __init__(self):
        self.x = r.randint(0,10)
        self.y = r.randint(0,10)

    def move(self):
        self.x -= 1
        print("我的位置是:", self.x, self.y)

class GoldFish(Fish):
    pass

class Carp(Fish):
    pass

class Salmon(Fish):
    pass

class Shark(Fish):
    def __init__(self):
        self.hungry = True

    def eat(self):
        if self.hungry:
            print("饿饿!!!!!!饿!!!!!!")
            self.hungry = False
        else:
            print("太撑了 吃不下咯!")

The construction method of shark covers the construction method of the parent class, which causes the x variable to not be initialized and an arithmetic operation error is reported in the move method. This can be solved by changing to the following two methods.

Recommended method

Because you can modify the parent class in one step, you don't need to call the parent class method code. For example, if you modify Fish to FishA, the Fish.__init__(self) in the method that is not recommended below should be changed to FishA.__init__(self)

class Shark(Fish):
    def __init__(self):
        super().__init__()
        self.isHungry = True

    def eat(self):
        if self.isHungry:
            print("饿饿!!!!!!饿!!!!!!")
            self.isHungry = False
        else:
            print("太撑了 吃不下咯!")

Not recommended method

class Shark(Fish):
    def __init__(self):
        Fish.__init__(self) #新增一句代码,调用父类构造方法初始化x
        self.hungry = True

    def eat(self):
        if self.hungry:
            print("饿饿!!!!!!饿!!!!!!")
            self.hungry = False
        else:
            print("太撑了 吃不下咯!")

Python supports multiple inheritance

It is not recommended to use multiple inheritance, because it may lead to unpredictable bugs

combination

class Turtle:
    def __init__(self,x):
        self.num = x

class Fish:
    def __init__(self,x):
        self.num = x

class Pool:
    def __init__(self, x, y):
        self.turtle = Turtle(x)
        self.fish = Fish(y)

    def print_num(self):
        print("水池有乌龟%s只,鱼%d条!" % (self.turtle.num, self.fish.num))

Class definition, class object and instance object

  • Class definitions are static, class objects and instance objects are dynamic
  • After using del to destroy the class definition, the existing class objects and instance objects can still function normally, but the objects cannot be instantiated through the class definition again
  • The class definition () instance comes out of the class object, once the member of the class object is changed, it becomes an instance object.
  • Can affect [members of class objects] through [class. member name], but not [members of instance objects]

The following is my personal guess, please let me know if you know

On the chestnut, it is not difficult to see why after C.count += 100, the count of instance objects a and b are affected, but the c instance object is not affected? It is found through observation that c.count has been modified, resulting in c.count not being affected by C.count (C is a class and also a class object), and the other two counts of a and b still remain unchanged, so Will be affected by class object C?

A bit similar to the immutability of C#'s string. For example, when a, b, and c are first instantiated, they all point to the same initial state instance object. When the member of c is modified, c points to the new The instance object of C.count is the initial state instance object modified by C.count, that is, the instance object pointed to by a and b, and c is naturally not affected. [To be confirmed, point of doubt ①]

On the chestnut, the modified cx will overwrite the original cx method and become an int type variable.

Bind

Python strictly requires a method to have an instance before it can be called. This restriction is actually the so-called binding concept of Python.

On the chestnut, self is not bound to B's printB method (that is, the first parameter of the method is not self)

You can view the member dictionary of the instance object or class by accessing the __dict__ attribute

Destroy class del

Use the del method to destroy

On the chestnut, although I destroyed the C class and cannot create a new C class object, the c object can still be used normally.

Class-related built-in methods

issubclass(classA, classB)

Judge whether classA is a subclass of classB, if it returns True, otherwise False

isinstance(obj, class)

Determine whether obj is an object of class

class can also be a class tuple, as long as obj belongs to one of the tuple's class objects, it returns True

hasattr(object, name)

Determine whether there are attributes in the object

getattr(obj, name [, default])

Get an attribute of the object

setattr(obj, name, value)

Assign a value to the object attribute, if there is no attribute, a new attribute assignment will be created

delattr(obj, name)

Delete an attribute in the object. Note: If it does not exist, an exception AttributeError will be raised. You can check for existence before deleting it.

property(fget=None, fset=None, fdel=None, doc=None)

property(...) binds the three methods (get, modify, delete) related to a property with the x property, and the x property directly manipulates the size, for example: c1.x=18 is equivalent to c1.setSize(18 ) The other operations are the same.

to sum up

Guess you like

Origin blog.csdn.net/qq_39574690/article/details/111561470