Python basic study notes 08-classes and objects inherit polymorphic class attributes and instance attributes, class methods and static methods

1. Classes and objects

1.1 Definition
Syntax:
class class name ():
code

1.2 Create an object
Syntax:
object name = class name ()

class Animal():
    def func(self):
        print("animal")

animal = Animal()
animal.func()

1.3 Attributes
Add object attributes outside the class:
syntax:
object name. attribute = value

Get object properties outside the class:
syntax:
object name. property

class Person():
    def func(self):
        print("person")

p = Person()
p.name = "Tom"
p.age = 18
print(f"姓名{p.name},年龄:{p.age}")

Get object attributes in the class:
syntax:
self. attribute name

class Person():
    def func(self):
        print(f"姓名:{self.name},年龄:{self.age}")

p = Person()
p.name = "Tom"
p.age = 18
p.func()

1.4 Magic Method
1.4.1 _ init _
Function: Initialize the object

class Person():
    def __init__(self):
        self.name = "Tom"
        self.age = 18
    def func(self):
        print(f"姓名:{self.name},年龄:{self.age}")

Note:
_ init _ is called by default when creating an object, no need to manually call (equivalent to C++ constructor)
_ init _ in the self parameter, does not need to be passed by the developer

# 带参数的_init_()
class Person():
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def func(self):
        print(f"姓名:{self.name},年龄:{self.age}")

1.4.2 _ str _
When using print to output an object, the memory address of the object is printed by default. If the _ str _ method is defined, the return data in this method will be printed. Used to output object status

class Person():
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __str__(self):
        return "Person"

p = Person("Tom",18)
print(p)	# Person

1.4.3 _ del _
When deleting an object, call the _ del _() method

class Person():
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __del__(self):
        print(f"姓名:{self.name},年龄:{self.age}")

p = Person("Tom",18)
del p

2. Inheritance

2.1 Syntax
class parent class name ():
code
class subclass name (parent class name):
code

Multiple inheritance:

class Father():
    def __init__(self):
        self.hair = "black"
    def __str__(self):
        return self.hair

class Mother():
    def __init__(self):
        self.hair = "brown"
    def _str_(self):
        return self.hair

class Son(Father,Mother):
    pass

s = Son()
print(s)

When a class has multiple parent classes, the properties and methods of the same name of the first parent class are used by default.
Subclasses can override the methods of the parent class

2.2 The subclass calls the properties and methods of the parent class with the same name

class Father():
    def __init__(self):
        self.hair = "black"
    def __str__(self):
        return self.hair

class Mother():
    def __init__(self):
        self.hair = "brown"
    def _str_(self):
        return self.hair

class Son(Father,Mother):
    def __init__(self):
        self.hair = "blond"
        #调用父类的方法,但是为保证调用到的也是父类的属性,必须在调用方法前调用父类的初始化
    def father_hair(self):
        Father.__init__(self)
    def mother_hair(self):
        Mother.__init__(self)
    def son_hair(self):
        # 如果先调用了父类的属性和方法,父类属性会覆盖子类属性故先调用子类的属性初始化
        self.__init__()
    def _str_(self):
        return self.hair

s = Son()
s.father_hair()
print(s)
s.mother_hair()
print(s)
s.son_hair()
print(s)

2.3 super() calls the parent class method
Syntax 1:
super(current class name, self). function()
Syntax 2:
super(). function()

    def parents_hair(self):
        super().__init__()
    def son_hair(self):
        super(Son,self).__init__()

2.4 Private authority
Syntax:
self.__ attribute name=value
self.__ function name():

class Father():
    def __init__(self):
        self.__money = 1000		# 私有权限
class Son(Father):
    pass

3. Polymorphism

Polymorphism is a way of using objects. Subclasses override parent methods and call the same parent methods of different subclass objects, which can produce different execution results.

class Father():
    def func(self):
        print("father")

class Son(Father):
    def func(self):
        print("son")

class Daughter(Father):
    def func(self):
        print("daughter")

class Person():
    def person_func(self,p):
        p.func()

s = Son()
d = Daughter()
p = Person()
p.person_func(s)
p.person_func(d)

4. Class attributes and instance attributes

The class attribute is the attribute owned by the class object, which is shared by all instance objects of the
class. The class attribute can be accessed using the class object or the instance object
. Syntax: class name. Attribute name.
Advantages of the class attribute:
when a certain item of data recorded is always consistent , Then define the class attributes.
Instance attributes require each object to open a separate memory space for recording data, while the class attributes are shared by all classes, occupying only one memory, which saves more memory space

Class attributes can only be modified through the class object, not through the instance object
. Syntax: class name. attribute name = value

5. Class methods and static methods

5.1 Class method The
decorator @classmethod needs to be used to identify it as a class method. For a class method, the first parameter must be a class object, usually cls is used as the first parameter

# 当方法中需要使用类对象时,定义类方法,类方法一般和类属性配合使用
class Father():
    __money = 100
    @classmethod
    def get_money(cls):
        return cls.__money

5.2 Static methods
need to be decorated with the decorator @staticmethod, static methods do not need to pass class objects nor instance objects,
static methods can also be accessed through instance objects and class objects

class Person():
    @staticmethod
    def func():
        print("Person")

Guess you like

Origin blog.csdn.net/qq_44708714/article/details/105041592