Python object-oriented programming class and instance inheritance and polymorphic isinstance

class Student(object):
    def __init__(self, name, gender):
        self.__name = name
        self.__gender = gender
    def set_gender(self, gender):
        if gender == 'male':
            self.__gender = gender
        elif gender == 'female':
            self.__gender = gender
        else:
            pass
    def get_gender(self):
        return self.__gender
# 测试:
bart = Student('Bart', 'male')
if bart.get_gender() != 'male':
    print('测试失败!')
else:
    bart.set_gender('female')
    if bart.get_gender() != 'female':
        print('测试失败!')
    else:
        print('测试成功!')
#下面的操作会导致实例增加一个新变量 变量名为__name
>>> bart.__name = 'New Name' # 设置__name变量!
>>> bart.__name
'New Name'

class

The class keyword, which inherits the object, represents the definition of a student class

Generally define __xxx as private variables, and the python interpreter will automatically rename the names of private variables to avoid direct references from the outside world;

例如:__nameThe variable is changed to_Student__name

Access to private objects in the class should be done through the get() and set() functions;

Inheritance and polymorphism

class Animal(object):
    def run(self):
        print('Animal is running...')
#继承Animal
class Dog(Animal):
    #覆盖父类的函数run()
    def run(self):
        print('Dog is running...')
    #拓展子类的新功能
    def eat(self):
        print('Eating meat...')
def run_twice(animal):
    animal.run()
    animal.run()

class Tortoise(Animal):
    def run(self):
        print('Tortoise is running slowly...')
>>> run_twice(Tortoise())
Tortoise is running slowly...
Tortoise is running slowly...

When we call the run_twice function, as long as the object has a run method, it can run smoothly! A function can be applied to a variety of classes, whether it is a parent class or a child class

isinstance

Used to query whether a variable belongs to a certain type, such as str, int or class

>>> isinstance('a', str)
True
>>> isinstance(123, int)
True
>>> isinstance(b'a', bytes)
True
>>> isinstance([1, 2, 3], (list, tuple))
True
>>> isinstance((1, 2, 3), (list, tuple))
True

>>> dir('ABC')
['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill']

to you() 

Can get all the properties and methods of the object;

getattr(), setattr()And hasattr()we can directly manipulate an object's state

>>> class MyObject(object):
...     def __init__(self):
...         self.x = 9
...     def power(self):
...         return self.x * self.x
...
>>> obj = MyObject()

>>> hasattr(obj, 'x') # 有属性'x'吗?
True
>>> obj.x
9
>>> hasattr(obj, 'y') # 有属性'y'吗?
False
>>> setattr(obj, 'y', 19) # 设置一个属性'y'
>>> hasattr(obj, 'y') # 有属性'y'吗?
True
>>> getattr(obj, 'y') # 获取属性'y'
19
>>> obj.y # 获取属性'y'
19
>>> getattr(obj, 'z', 404) # 获取属性'z',如果不存在,返回默认值404
404
>>> fn = getattr(obj, 'power') # 获取属性'power'并赋值到变量fn
>>> fn # fn指向obj.power
<bound method MyObject.power of <__main__.MyObject object at 0x10077a6a0>>
>>> fn() # 调用fn()与调用obj.power()是一样的
81

getattr(), setattr()Andhasattr()也可以用在方法上

The properties of the class can be accessed directly without instantiation, and can be accessed by all instances

class Student(object):
    count = 0

    def __init__(self, name):
        self.__name = name
        Student.count = Student.count + 1
# 测试:
if Student.count != 0:
    print('测试失败!')
else:
    bart = Student('Bart')
    if Student.count != 1:
        print('测试失败!')
    else:
        lisa = Student('Bart')
        if Student.count != 2:
            print('测试失败!')
        else:
            print('Students:', Student.count)
            print('测试通过!')

Reference source: https://www.liaoxuefeng.com/wiki/1016959663602400/1017497232674368

Guess you like

Origin blog.csdn.net/li4692625/article/details/109501079