python面向对象进阶

元类

首先,类也是一种对象,只要使用关键字class,python解释器在执行的时候就会创建一个对象。你就可以给他赋值一个变量、拷贝它、增加属性、将它作为函数参数进行传递。

使用type创建类

type可以动态的创建类,它可以接受一个类的描述作为参数,然后返回一个类。

使用方法:type(类名,由父类名称组成的元组(可以为空),包含属性的字典)

来看一个实例:

```python
test = type("test",(),{})#定义一个test类
a = test()#创建一个test类的实例对象
print(a)
print(test)
```

输出结果:

使用type创建带有属性的类

type接受一个字典来为类定义属性:

```python
Test = type('Test',(),{'flag':True})
```

可以翻译为:

```python
class test(object):
    flag=True

print(test)
print(test.flag)
```

输出结果:

也可以向这个类继承:

```python
test = type("test",(),{})#定义一个test类
class test:
    flag = True
test2 = type('test2',(test,),{})
print(test2)
print(test2.flag)
```

输出结果:

使用type创建带有方法的类

添加实例方法

```python
test = type("test",(),{})#定义一个test类
class test:
    flag = True

def echo_bar(self):
    print(self.bar)

test2 = type('test2',(test,),{'echo_bar':echo_bar})
a = hasattr(test,'echo_bar')#判断test类中,是否有echo_bar这个属性方法
print(a)

b = hasattr(test2,'echo_bar')#判断test2类中,是否有echo_bar这个属性方法
print(b)
```

输出结果:

添加静态方法

```python
test = type("test",(),{})#定义一个test类
class test:
    flag = True

def echo_bar(self):
    print(self.bar)

@staticmethod
def testStatic():
    print("test staticmethod")

test2 = type('test2',(test,),{'echo_bar':echo_bar,'testStatic':testStatic})
test2.testStatic()
```

输出结果:

添加类方法

```python
test = type("test",(),{})#定义一个test类
class test:
    flag = True

def echo_bar(self):
    print(self.bar)

@classmethod
def testClass(cls):
    print("test class method")

test2 = type('test2',(test,),{'echo_bar':echo_bar,'testClass':testClass})
test2.testClass()
```

输出结果:

更多内容请见

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值