你所需要的,不仅仅是一个好用的代理。
class Food(object):
"定义一个食物类"
pass
print(Food.__doc__)
#输出
定义一个食物类
__module__ 表示当前操作对象在哪个模块
__class__ 表示当前操作对象的类是什么
class A(object):
def __init__(self, name):
self.name = name
from local.obj import A
a = A('bigberg')
print(a.__module__)
print(a.__class__)
# 输出
local.obj # local.obj , 输出模块
<class 'local.obj.A'> # local.obj.A , 输出类
通过类创建对象时,自动触发执行
class Person(object):
country = 'CN' # 公有属性
def __init__(self, name, age, gender, province):
self.name = name
self.age = age
self. gender = gender
self.province = province
p = Person('bigberg', 22, 'M', 'zhejiang')
注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的。
class Person(object):
country = 'CN'
def __init__(self, name, age, gender, province):
self.name = name
self.age = age
self. gender = gender
self.province = province
def __del__(self):
print("该对象已经被删除!")
p = Person('bigberg', 22, 'M', 'zhejiang')
print(p.name)
del p
print(p.age)
# 输出
bigberg
该对象已经被删除!
Traceback (most recent call last):
File "G:/python/untitled/study6/类的特殊成员.py", line 34, in <module>
print(p.age) NameError: name 'p' is not defined
把类中的成员以字典的形式打印出来
1 class Person(object):
2
3 country = 'CN'
4
5 def __init__(self, name, age, gender, province):
6 self.name = name
7 self.age = age
8 self. gender = gender
9 self.province = province
10
11 def speak(self, language):
12 print("%s mother language is %s" % (self.name, language))
13
14
15 p = Person('bigberg', 22, 'M', 'zhejiang')
16
17 # 获取类的成员,即:构造函数的属性
18 print(Person.__dict__)
19
20 #输出: {'speak': <function Person.speak at 0x0000025CCBACE510>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__doc__': None, '__init__': <function Person.__init__ at 0x0000025CCBACE488>, 'country': 'CN', '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Person' objects>}
21
22
23 # 获取对象 p 的成员
24 print(p.__dict__)
25
26 #输出: {'name': 'bigberg', 'province': 'zhejiang', 'gender': 'M', 'age': 22}
View Code
class Person(object):
def __init__(self):
pass
def __call__(self, *args, **kwargs):
print('hello,world')
p = Person() # 执行 __init__
p() # 执行 __call__
# 输出
hello,world
1 class Person(object):
2
3 def __init__(self, name):
4 self.name = name
5
6 def __call__(self, *args, **kwargs):
7 print('hello,world')
8
9 def __str__(self):
10 return "It's a good day."
11
12 def speak(self):
13 return "%s is giving a speech." % self.name
14
15 p = Person('bigberg')
16 p.speak()
17 print(p)
18
19 #输出
20 It's a good day.
View Code