python 创建类_python 用type()创建类
type()可以查看一個(gè)類型,也可以查看變量的類型
class Hello1(object):
def hello(self, name = 'world'):
print('Hello, %s' % name)
h1 = Hello1()
h1.hello()
print(type(Hello1))
print(type(h1))
輸出:
Hello, world
#Hello是一個(gè)class, 它的類型就是type
#h1是一個(gè)實(shí)例,它的類型就是class Hello1
type()函數(shù)既可以返回一個(gè)對(duì)象的類型,也可以創(chuàng)建出新的class,如用type()函數(shù)創(chuàng)建出Hello類而無需通過class Hello(object):
def fn(self, name = 'world'): #先定義一個(gè)函數(shù)
print('Hello, %s' % name)
Hello = type('Hello', (object, ), dict(hello=fn)) #創(chuàng)建Hello class,傳入class的名稱,繼承的父類集合class的方法名與函數(shù)綁定,這里我們把fn綁定到hello上
h = Hello()
h.hello()
print(type(Hello))
print(type(h))
輸出:
Hello, world
要?jiǎng)?chuàng)建Hello calss, 需要給type()傳入3個(gè)參數(shù):
1. class的名稱,
2. 繼承的父類集合,注意Python支持多重繼承,如果只有一個(gè)父類,別忘了tuple的單元素寫法
3. class的方法名稱與函數(shù)綁定,這里我們是把fn綁定到方法名hello上
用type()創(chuàng)建的class和直接寫class是完全一樣的
總結(jié)
以上是生活随笔為你收集整理的python 创建类_python 用type()创建类的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 企业级 Spring Boot 教程 (
- 下一篇: 【企业架构】什么是数据架构? 管理数据的