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