内置函数type

使用type创建带有属性的类

type接受一个字典来为类定义属性,因此

>>>Foo=type('Foo',(),{'bar':True})

可以翻译为:

>>>class Foo(object):
...            bar=True

并且可以将FOO当成一个普通的类一样使用:

>>>print (Foo)
<class '__main__.Foo'>
>>>print(Foo.bar)
True
>>>f=Foo()
>>>print(f)
<__main__.Foo object at 0x8a9b84c>
>>>print(f.bar)
True

当然,你可以向这个类继承,所以,如下的代码:

>>>class FooChild(Foo):
...        pass

就可以写成:

>>>FooChild=type('FooChild',(Foo,),{})
>>>print(FooChild)
<class '__main__.FooChild'>
>>>print(FooChild.bar) #bar属性是由Foo继承而来

注意:
type的第二个参数,元组中是父类的名字,而不是字符串
添加的属性是类属性,并不是实例属性

使用type创建带有方法的类

类增加方法,只需要定义一个带有恰当签名的函数并将其作为属性赋值即可

添加实例方法

>>>def echo_bar(self):          #定义了一个普通函数
    ...      print(self.bar)
>>>FooChild=type('FooChild',(Foo,),{'echo_bar':echo_bar})
#FooChild类中的echo_bar属性,指向了上面定义的函数
>>>hasattr(Foo,'echo_bar') #判断Foo类中,是否有echo_bar这个属性
>>>False
>>>hassattr(FooChild,'echo_bar') #判断FooChild类中,是否有echo_bar这个属性
>>>True
>>>my_foo=FooChild()
>>>my_foo.echo_bar()
True

添加静态方法

>>>@staticmethod
...     def testStatic():
...            print("static method...")
>>>Foochild=type('Foochild',(Foo,),{"echo_bar":echo_bar,"testStatic"
...:testStativ})
>>>fooclid=Foochild()
>>>fooclid.test.Static
<function __main__.testStatic>
>>>fooclid.testStatic()
static  method...
>>>fooclid.echo_bar()
True

添加类方法

>>>@classmethod
 ....  def testClass(cls):
              print(cls.bar)
>>>Foochild=type('Foochild',(Foo,),{echo_bar":echo_bar,"testStatic"
...:testStativ,"testClass":testClass})
>>>fooclid=Foochild()
>>>fooclid.testClass()
True

可以看到,在python中,类也是对象,可以动态的创建类。使用关键字 class时python在幕后做的事情,就是通过元类来实现的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值