标签:__ 10 name self day07 def print Foo 类中
__author__ = "Alex Li"
import os
# os.system()
# os.mkdir()
class Dog(object):
'''这个类是描述狗这个对象的'''
def __init__(self,name):
self.name = name
self.__food = None
# 把一个方法变成一个静态属性
@property #attribute
def eat(self):
print("%s is eating %s" %(self.name,self.__food))
#保证能给属性赋值
@eat.setter
def eat(self,food):
print("set to food:",food)
self.__food = food
#保证能够删除属性
@eat.deleter
def eat(self):
del self.__food
print("删完了")
def talk(self):
print("%s is talking"% self.name)
#__call__ 对象后面加括号,触发执行
def __call__(self, *args, **kwargs):
print("running call",args,kwargs)
#__str__ 如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。
def __str__(self):
return "<obj:%s>" %self.name
Dog("ChenRonghua")(1,2,3,name=333)
d = Dog("ChenRonghua")
d(1,2,3,name=333)
print(Dog.__doc__) #输出:类的描述信息
print(Dog.__dict__) #打印类里的所有属性,不包括实例属性
print(d.__dict__) #打印所有实例属性,不包括类属性
print(d.__str__)
getitem.py
__author__ = "Alex Li"
#用于索引操作,如字典。以上分别表示获取、设置、删除数据
class Foo(object):
def __init__(self):
self.data = {}
def __getitem__(self, key):
print('__getitem__', key)
return self.data.get(key)
def __setitem__(self, key, value):
print('__setitem__', key, value)
self.data[key] =value
def __delitem__(self, key):
print('__delitem__', key)
obj = Foo()
obj['name'] = "alex"
print(obj['name'])
print(obj.data)
del obj["sdfdsf"]
# result = obj['k1'] # 自动触发执行 __getitem__
# obj['k2'] = 'alex' # 自动触发执行 __setitem__
# del obj['k1']
new.py
__author__ = "Alex Li"
# class Foo(object):
# def __init__(self, name):
# self.name = name
#
# f = Foo("alex")
# print(type(f))
# print(type(Foo))
# def func(self):
# print('hello Alex')
#
# # Foo = type('Foo', (object,), {'func': func})
# # type第一个参数:类名
# # type第二个参数:当前类的基类
# # type第三个参数:类的成员
# Foo = type('Foo', (object,), {'talk': func})
#
# f = Foo()
# f.talk()
# print(type(Foo))
def func(self):
print('hello %s' %self.name)
def __init__(self,name,age):
self.name = name
self.age = age
#f对象是Foo类的一个实例,Foo类对象是 type 类的一个实例
Foo = type('Foo', (object,), {'talk': func,
'__init__':__init__})
f = Foo("Chrn",22)
f.talk()
print(type(Foo))
标签:__,10,name,self,day07,def,print,Foo,类中 来源: https://www.cnblogs.com/netflix/p/14855019.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。