python type创建类

type不仅可以查看数据类型,还可以创建类

#type(类名,继承类,属性方法)
Parent = type("Parent",(object,),{"age":"18","func":lambda self,x:print("hello type",self,x)})
parent = Parent()
print(parent.age)
parent.func(6)

#定义静态方法
Parent = type("Parent",(object,),{"age":"18","func":staticmethod(lambda x:print("static method",x))})
parent = Parent()
print(parent.age)
parent.func(8)
print(Parent.age)
Parent.func(8)

#定义类方法
Parent = type("Parent",(object,),{"age":"18","func":classmethod(lambda cls,x:print("class method",cls,x))})
parent = Parent()
print(parent.age)
parent.func(100)
print(Parent.age)
Parent.func(100)

#定义实例属性
def greet(self):
    print(f"Hello, my name is {self.name} and I am {self.age} years old.")

Person = type("Person", (object,), {
    "species": "Human",       # 类属性
    "__init__": lambda self, name, age: setattr(self, 'name', name) or setattr(self, 'age', age),       # 构造方法,用于设置实例属性
    "greet": greet            # 实例方法
})

p = Person("Alice", 30)
p.greet()  # Output: Hello, my name is Alice and I am 30 years old.
print(p.species)  # Output: Human
18
hello type <__main__.Parent object at 0x000002AB2C1DFFD0> 6
18
static method 8
18
static method 8
18
class method <class '__main__.Parent'> 100
18
class method <class '__main__.Parent'> 100
Hello, my name is Alice and I am 30 years old.
Human

 

posted @ 2025-10-24 11:35  我的腹肌不见了  阅读(3)  评论(0)    收藏  举报