» Python快速入门 » 3. 高级篇 » 3.1 类与对象

类与对象

创建类

class Fruit:
    name = "" # Member Field

    # Constructor method
    def __init__(self, name):
        self.name = name

    # Member method
    def show(self):
        print("Name:", self.name)

继承

class Banana(Fruit):

    def eat(self):
        print(f"{self.name} is yummy!")

b = Banana("Blue Java Banana")
# inherited method: show
b.show() # Name: Blue Java Banana
# subclass's own method: eat
b.eat() # Blue Java Banana is yummy!

覆盖

class Apple(Fruit):
    nutrition = [1, 2, 3]

    def show(self):
        print("Name:", self.name, "Nutrition Facts:", self.nutrition)

a = Apple("Big Apple")

# overrided method
a.show() # Name: Big Apple Nutrition Facts: [1, 2, 3]

通过 @property 设置 Getters 和 Setters

Python 通过内置 @property 装饰器 来简化 getters 和 setters 的实现。

class RoomTemperature:
    
    def __init__(self, temperature=0):
        self.__temperature = temperature

    @property
    def celsius(self):
        return self.__temperature

    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("impossible temperature")
        self.__temperature = value

    @property
    def fahrenheit(self):
        return self.__temperature * 9 / 5 + 32

rt = RoomTemperature(25)
# with the help of @property decorator, method access is as simple as field access
print(rt.celsius) # 25
print(rt.fahrenheit) # 77.0

rt.celsius = 500 # OK
rt.celsius = -500 # ValueError: impossible temperature

类方法

类方法是一种在调用时将所调用的类(或实例所属的类)作为第一个参数传递进去的方法。可很方便地用作该类的工厂函数。

class Fruit:
    def foo(self, x):
        print(f"executing foo {self}, {x}")

    @classmethod
    def class_foo(cls, x):
        print(f"executing class_foo {cls}, {x}")

f = Fruit()
f.foo(42) # executing foo <__main__.Fruit object at 0xf5add8>, 42
f.class_foo(42) # executing class_foo <class '__main__.Fruit'>, 42
Fruit.class_foo(42) # executing class_foo <class '__main__.Fruit'>, 42

静态方法

静态方法是在类中定义方法的另一种方式。它在逻辑上属于该类,但它就像一个普通独立函数一样,对调用它的类或实例一无所知。它只获取传递的参数,不像类方法等有隐含的第一个参数。

class TemperatureUtil:
    @staticmethod
    def celsius_to_fahrenheit(celsisu):
        return celsisu * 9 / 5 + 32

print(TemperatureUtil.celsius_to_fahrenheit(25)) # 77.0

魔法方法

__str__ 方法可自定义该类作为字符串呈现时候的形式。

__str__

class Fruit:

    def __init__(self, name):
        self.__name = name

print(Fruit("banana")) # <__main__.Fruit object at 0xc24fd8>

# with __str__ method
class Fruit:

    def __init__(self, name):
        self.__name = name

    def __str__(self):
        return f"Name: {self.__name}"

print(Fruit("banana")) # Name: banana

__del__ 方法可当做析构函数。它在对象被垃圾回收时调用。

__del__

class Fruit:

    def __del__(self):
        print("I'm gone!")

f = Fruit()
del f # I'm gone!

代码挑战

修改编辑器中代码使得类实例呈现如右效果:Tom(22) Skills: C++,Python,JavaScript

Loading...
> 此处输出代码运行结果
上页
下页