python中的类,类同样是一种对象,只要使用关键字class,python解释器执行的时候就会创建一个对象
class Test(object):
pass
test = Test()
print(test)
判断一个对象是否在某个类中--->
hasattr(obj,str)
class Test(object):
pass
test = Test()
print(test)
print(Test)
def info(o):
print(o)
可以将类作为参数传递给函数
info(test)
可以为类添加新的属性:
class Test(object): passtest = Test()print(test)print(Test) def info(o): print(o) info(test) print(hasattr(Test,‘new attribute‘))Test.new_attribute = ‘haha‘print(hasattr(Test,‘new_attribute‘))print(Test.new_attribute) 运行结果:
<__main__.Test object at 0x00000198F952C198>
<class ‘__main__.Test‘>
<__main__.Test object at 0x00000198F952C198>
False
True
haha
注:判断一个对象是否在类中,使用hasattr,格式hasattr(obj,str)
13.02python语言基础(动态创建类)
动态创建类
def choose_name(name):
if name == 'haha'
class haha(object):
pass
return haha
else:
class heihei(object):
pass
return heihei
my_class = choose_name('haha')
print(my_class)
print(my_class())
原文地址:https://www.cnblogs.com/mylove-821717420/p/9597258.html
时间: 2024-10-19 17:13:31