创建Python类的7个层次

创建Python类的7个层次

  1. 数据类--不使用 __init__创建类
  1. 基本类 我们能写的最简单的类。
class Dog:
    pass
dog = Dog()   
# initializing # 初始化
  1. 带有基本方法的基本类 与其使用pass,什么也不做,不如添加一个简单的方法。
class Dog:
    def bark(self):
        print("woof")
dog = Dog()
dog.bark()   # woof
  1. 带有__init__方法的基本类

让我们添加一个__init__魔法方法,它允许我们定制我们的类,并为某些属性分配不同的值。


class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def bark(self):
        print("woof)
        
dog1 = Dog("
rocky", 4)   
# name="
rocky" age=4

dog2 = Dog("
lucky", 5)   
# name="
lucky" age=5
  1. 继承于另一个类的类

通过使用class Dog(Animal)语法,我们使Dog类继承于Animal类。这意味着,动物类中的任何属性或方法也会在狗类中出现。

class Animal:
    def speak(self):
        print("hello")
class Dog(Animal):
    pass
dog = Dog()
dog.speak()   # hello
  1. __init__继承于另一个类的类

如果我们的子类有一个不同于父类的__init__方法,我们可以在子类中使用super().__init__。这实质上是在子类的 __init__ 方法中调用父类的__init__方法。

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width
    def area(self):
        return self.length * self.width
        
class Square(Rectangle):
    def __init__(self, length):
        super().__init__(length, length)   
        # Rectangle's __init__

在这里,在 Square 的 __init__ 函数中,我们调用了super().__init__函数,它本质上就是 Rectangle 的 __init__ 函数。由于在 Square 中 length==width,我们将 length 传递两次到 super().__init__

r = Rectangle(5, 4)
r.area()   # 20
s = Square(3)
s.area()   # 9
  1. 数据类

厌倦了写__init__方法?试试数据类。


from dataclasses import dataclass
@dataclass
class Dog:
    name: str
    age: int
    def bark(self):
        print(f "woof name={self.name} age={self.age}")
dog = Dog("rocky", 4)
dog.bark() # woof name=rocky age=4
  1. 从type()创建一个类

考虑一下下面这个继承自Animal的普通Dog类。

class Animal:
    def speak(self):
        print("hello")
class Dog(Animal):
    def __init__(self, name, age):
        self.name = name
        self.age = age

我们可以不使用class关键字来创建狗类--我们可以使用type()函数来代替。

def init(self, name, age):
    self.name = name
    self.age = age

这一行创建了狗类

# class = type(classname, bases, dict)
狗 = type("Dog", (Animal,), {"__init__":init})
dog = Dog("rocky", 4)

结语 希望这篇文章对你有帮助,有参考价值

本文由 mdnice 多平台发布

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值