__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))