Python advanced objects and classes

class

Class attribute

Class attribute: it can be shared by the current class instance object, which is called by the class name,
similar to the static variable of the class

class Student:
	# 所有类实例对象都可以操作
	school='牛津大学'

print(Student.school)

Class method

Class method: similar to a static method, called by the class name, you need to add a modifier @classmethod
to manipulate class attributes. The
default parameter clsrepresents the current class, which clsis the abbreviation of class

class Student:
	# 类属性
	school='牛津大学'
	
	# 类方法
	@classmethod
	def printSchool(cls):
		print(cls.school)

Static method

Static method: similar to class method, the difference is that the current class attribute cannot be called, there is no default attribute cls, and it is also called by the class name. The
modifier @staticmehtod
usually defines some methods that are not related to the class.

class Student:

	@staticmethod
	def caculate(a,b):
	'''
	计算参数a和参数b的和
	'''
	return a+b

Object

Constructor

In python, all class constructors are called __init__, and all instance methods have a default parameter self. We don’t need to selfassign values to the passed parameters. It selfrepresents the current object, and the interpreter automatically interprets it.

class Student:
	
	def __init__(self,name,age):
		'''
		第一参数必须是self
		通过self.的方式创建对象属性
		下面实例给student对象创建两个对象属性name,age
		'''
		self.name=name
		self.age=age

stu=Student('张三',18)

Private properties/methods

Python does not have strict access control on the members of the class, which is different from other object-oriented. There are the following points about private properties and private methods:

  1. Usually we agree that the attributes starting with the two underscores are private, and the others are public
  2. Private properties or methods cannot be directly accessed outside the class
  3. Private properties or methods can be directly accessed inside the class
  4. The outside of the class can access private attributes or methods through "_class name__private attribute (method) name"
class Person:

    def __init__(self,name,age):
        self.__name=name
        self.__age=age
    
    def toString(self):
        '''
        在类内部访问类的私有属性
        '''
        print('name:{0}age:{1}'.format(self.__name,self.__age))

p=Person('张三',18)
p.toString()

'''
一定要非法访问,可以通过_类名__属性名的方式访问
'''
print(p._Person__name)
print(p._Person__age)
'''
在外部直接访问私有属性会直接报错的
'''
print(p.__name)

Insert picture description here

class Person:

    def __init__(self):
        print('构造方法被执行了')
        self.__work()
    
    def __work(self):
        '''
        私有方法
        '''
        print('我会努力工作')
    
p=Person()
p.__work()

Insert picture description here

getter/setter method

Normal way

'''
普通方式给类属性设置get和set方法
'''
class Person:

    def __init__(self,name):
        '''
        构造方法
        '''
        # 属性一定要私有化
        self.__name=name

    def set_name(self,name):
        self.__name=name
    
    def get_name(self):
        return self.__name

p=Person('李四')
print(p.get_name())
p.set_name('张三')
print(p.get_name())

Insert picture description here

Use decorator @property to simplify

The @property decorator can make the method call like a property

class Person:

    def __init__(self,salay):
        # 属性必须私有化
        self.__salay=salay

    @property
    def salay(self):
        '''
        get方法
        '''
        return self.__salay

    @salay.setter
    def salay(self,salay):
        '''
        set方法
        '''
        if salay>0:
            self.__salay=salay
        else :
            print('输入值不能低于0')

p=Person(3000)
print(p.salay)
p.salay=-2000
print(p.salay)
p.salay=8000
print(p.salay)

Insert picture description here

Object (instance) method

All instance methods have a default parameter self, we don’t need to selfassign a value to the passed parameter, which selfrepresents the current object, and the interpreter automatically interprets the
calling method: instance name. method name

class Student:
	
	def __init__(self,name,age):
		'''
		第一参数必须是self
		通过self.的方式创建对象属性
		下面实例给student对象创建两个对象属性name,age
		'''
		self.name=name
		self.age=age

	def toString(self):
		'''
		打印name和age
		'''
		print('name={0},age={1}'.format(self.name,self,age))
	

stu=Student('张三',18)

Destructor

__del__Methods are called destructors in python and are used to implement the operations required when the object is destroyed.
Python realizes 自动的垃圾回收that when the object is not referenced (when the reference counter is 0), the __del__function of the object is called by the garbage collector.
We can also deldelete the object through the keyword , so as to achieve the calling __del__method.
Generally, the system automatically provides a __del__method. Define destructor method

class Student:
    
    def __init__(self):
        '''
        构造函数
        '''
        print('初始化一个student对象'+str(id(self)))
        pass

    def __del__(self):
        '''
        析构函数
        '''
        print('id:'+str(id(self))+'被销毁')

stu01=Student()
stu02=Student()

result
**Insert picture description here**

Object call function and callable object

Every object has a callfunction, which 对象名()is called by way

class Person:
    def __init__(self):
        '''
        构造函数
        '''
        print('创建了一个对象:'+str(self))

    def __call__(self,salary):
        '''
        call函数
        '''
        yearsSalary=salary*12
        daySalary=salary//27.5

        return {
    
    
            'yearsSalary':yearsSalary,
            'daySalary':daySalary
        }

p=Person()

print(p(3000))

Insert picture description here

Method overloading

There is no overloading of methods in python. Python does not support overloading.
There are multiple methods with the same name. Only the last method is valid, and the rest are invalid.

class Student:

    def hello(self):
        print('hello world')


    def hello(self,message):
        print(message)
    
stu=Student()
stu.hello()

result
Insert picture description here

The dynamics of python

Dynamically add methods to the class

class Person:

    def work(self):
        print('努力工作')

# 在类的外面定义个方法
def play_games(s):
    print(str(id(s))+'愉快的玩游戏')

# 将玩游戏这个方法添加给Person
Person.play_game=play_games

p=Person()
p.work()
p.play_game()

Insert picture description here

Dynamically modify methods for classes

class Person:

    def work(self):
        print('努力工作')

# 在类的外部定义一个work方法
def works(s):
    print(str(id(s))+'说:好好工作,努力学习')

# 将person的work赋值等于work()方法
Person.work=works

p=Person()
p.work()
	

Insert picture description here

isinstance function

Parameter 1: Object
Parameter 2: Class
Function: Used to judge whether the current object belongs to the current class

class Student:

    def __init__(self):
        pass

    pass

stu=Student()

print(isinstance(stu,Student))# 结果为True

Object-oriented features (encapsulation, inheritance, polymorphism)

Package

Encapsulation is an important principle of the object-oriented method, which is to combine the properties and operations (or services) of the object into an independent whole, and hide the internal implementation details of the object as much as possible.

class Person:

    def __init__(self,name,age):
        self.__name=name
        self.__age=age
    
    @property
    def name(self):
        print('name的get方法')
        return self.__name
    
    @name.setter
    def name(self,name):
        print('name的set方法')
        self.__name=name

    @property
    def age(self):
        print('age的get方法')
        return self.__age

    @age.setter
    def age(self,age):
        print('age的set方法')
        self.__age=age

p=Person('张三',18)
print(p.name)
p.name='李四'
print(p.name)
print(p.age)
p.age=20
print(p.age)

result
Insert picture description here

inherit

​ Inheritance means that the subclass inherits the characteristics and behaviors of the parent class, so that the subclass object (instance) has the instance domain and methods of the parent class, or the subclass inherits methods from the parent class, so that the subclass has the same behavior as the parent class. Of course, if there are private attributes (private modification) in the parent class, the subclass cannot be inherited.
Python supports multiple inheritance

Single inheritance

class Father:

    def __init__(self,name='暂未设置',age=28):
        '''
        构造函数
        '''
        self.__name=name
        self.__age=age
    
    def toString(self):
        print('name:{0}age:{1}'.format(self.__name,self.__age))


f=Father('张三',30)
f.toString()


class Children(Father):

    def __init__(self,name='暂未设置',age=18):
        '''
        子类需要显式的调用父类的构造函数
        \n不调用解释器不会去执行父类的构造函数
        '''
        self.__name=name
        self.__age=age
        Father.__init__(self)

c=Children()
c.toString()

Multiple inheritance

class a:
    def say(self):
        print('你好,我是a类说的第一句话')

class b:
    def hello(self):
        print('b说的话')
    
class c(a,b):
    pass

c=c()
c.hello()
c.say()

result
Insert picture description here

Polymorphism

​ Polymorphism is the ability to have multiple different manifestations or forms of the same behavior.

class Man:

    def eat(self):
        print('吃饭方法')
    pass

class Chinese(Man):

    def eat(self):
        print('中国人吃饭用叉子')
    pass

class English(Man):

    def eat(self):
        print('英国人吃饭用筷子')
        pass
    pass

class Indian(Man):

    def eat(self):
        print('印度人吃饭用手')
        pass
    pass

def runEat(man):
    if isinstance(man,Man):
        man.eat()
    else :
        print('非man')

runEat(Chinese())
runEat(English())
runEat(Indian())

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42418169/article/details/109620887