Basic knowledge of Python (7): classes, objects and magic methods

Class and object

1. Object = Property + Method

Objects are instances of classes. In other words, the class mainly defines the structure of the object, and then we create the object using the class as a template. The class not only contains method definitions, but also contains data shared by all instances.

  • Package: information hiding technique
    that we can use keywords classdefined Python class keyword followed by the name of the class, and classes to achieve a semicolon.
    【example】
class Turtle:  # Python中的类名约定以大写字母开头
    """关于类的一个简单例子"""
    # 属性
    color = 'green'
    weight = 10
    legs = 4
    shell = True
    mouth = '大嘴'
    # 方法
    def climb(self):
        print('我正在很努力的向前爬...')
    def run(self):
        print('我正在飞快的向前跑...')
    def bite(self):
        print('咬死你咬死你!!')
    def eat(self):
        print('有得吃,真满足...')
    def sleep(self):
        print('困了,睡了,晚安,zzz')
tt = Turtle()
print(tt)
# <__main__.Turtle object at 0x0000007C32D67F98>
print(type(tt))
# <class '__main__.Turtle'>
print(tt.__class__)
# <class '__main__.Turtle'>
print(tt.__class__.__name__)
# Turtle
tt.climb()
# 我正在很努力的向前爬...
tt.run()
# 我正在飞快的向前跑...
tt.bite()
# 咬死你咬死你!!
# Python类也是对象。它们是type的实例
print(type(Turtle))
# <class 'type'>
  • Inheritance: a mechanism for subclasses to automatically share data and methods between parent classes
    [example]
class MyList(list):
    pass
lst = MyList([1, 5, 2, 7, 8])
lst.append(9)
lst.sort()
print(lst)
# [1, 2, 5, 7, 8, 9]
  • Polymorphism: different objects respond to different actions in the same method
    [example]
class Animal:
    def run(self):
        raise AttributeError('子类必须实现这个方法')
class People(Animal):
    def run(self):
        print('人正在走')
class Pig(Animal):
    def run(self):
        print('pig is walking')
class Dog(Animal):
    def run(self):
        print('dog is running')
def func(animal):
    animal.run()
func(Pig())
# pig is walking

2. What is self?

Python is selfequivalent to the C ++ thispointer.
【example】

class Test:
    def prt(self):
        print(self)
        print(self.__class__)
t = Test()
t.prt()
# <__main__.Test object at 0x000000BC5A351208>
# <class '__main__.Test'>

There is only one special difference between class methods and ordinary functions-they must have an additional first parameter name (corresponding to the instance, that is, the object itself), which is by convention self. When calling the method, we need to explicitly provide the parameters selfcorresponding to the parameters.
【example】

class Ball:
    def setName(self, name):
        self.name = name
    def kick(self):
        print("我叫%s,该死的,谁踢我..." % self.name)
a = Ball()
a.setName("球A")
b = Ball()
b.setName("球B")
c = Ball()
c.setName("球C")
a.kick()
# 我叫球A,该死的,谁踢我...
b.kick()
# 我叫球B,该死的,谁踢我...

3. Python's magic method

It is said that Python objects are born with some magical methods. They are everything in object-oriented Python...
They are special methods that can add magic to your class...
If your object implements one of these methods, then this method Will be called by Python under special circumstances, and all of this happens automatically... The
class has a __init__(self[, param1, param2...])magic method called , which is automatically called when the class is instantiated.
【example】

class Ball:
    def __init__(self, name):
        self.name = name
    def kick(self):
        print("我叫%s,该死的,谁踢我..." % self.name)
a = Ball("球A")
b = Ball("球B")
c = Ball("球C")
a.kick()
# 我叫球A,该死的,谁踢我...
b.kick()
# 我叫球B,该死的,谁踢我...

Guess you like

Origin blog.csdn.net/OuDiShenmiss/article/details/107828053