python 中用type 创建类

class Foo:
    age = 95
    def __init__(self,name, phone):
        self.name = name
        self.phone = phone

    def phone_number(self):
        return self.phone
print(Foo)
print(Foo.__dict__)
print('===========================================')
f = Foo('raimond', 123456)
print(f)
print(f.__dict__)
print(f.phone_number())

C:\Users\user\AppData\Local\Programs\Python\Python36\python.exe “C:/Users/user/PycharmProjects/hellow python/test.py”
<class ‘main.Foo’>
{‘module’: ‘main’, ‘age’: 95, ‘init’: <function Foo.init at 0x0000026570DC3048>, ‘phone_number’: <function Foo.phone_number at 0x0000026570F56C80>, ‘dict’: <attribute ‘dict’ of ‘Foo’ objects>, ‘weakref’: <attribute ‘weakref’ of ‘Foo’ objects>, ‘doc’: None}
===========================================

<main.Foo object at 0x0000026570DBF828>
{‘name’: ‘raimond’, ‘phone’: 123456}
123456

Process finished with exit code 0

以下通过type 来实现


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

def phone_number(self):
    return self.phone

Foo = type('Foo', (object,), {'age':95, '__init__':__init__, 'phone_number': phone_number})

print(Foo)
print(Foo.__dict__)
print('===========================================')

f = Foo('raimond', 123456)
print(f)
print(f.__dict__)
print(f.phone_number())

C:\Users\user\AppData\Local\Programs\Python\Python36\python.exe “C:/Users/user/PycharmProjects/hellow python/test.py”
<class ‘main.Foo’>
{‘age’: 95, ‘init’: <function init at 0x00000294FDB53E18>, ‘phone_number’: <function phone_number at 0x00000294FF833048>, ‘module’: ‘main’, ‘dict’: <attribute ‘dict’ of ‘Foo’ objects>, ‘weakref’: <attribute ‘weakref’ of ‘Foo’ objects>, ‘doc’: None}
===========================================

<main.Foo object at 0x00000294FF82FB38>
{‘name’: ‘raimond’, ‘phone’: 123456}
123456

Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值