class FirstClass: # define a class object
def setdata(self,value): # define class methods
self.data = value # self is the instance
def display(self):
print(self.data) # self.data:per instance
x = FirstClass()
y = FirstClass()
x.setdata('King Arthur')
y.setdata(3.1415926)
x.display() # make new instances
y.display() # Each is a new namespace
King Arthur
3.1415926
x.data = "New Value" # Can set/get attributes
x.display( ) # Outside the class too
x.anothername = 'spam' # Can set new attributes here too!
New Value
class SecondClass(FirstClass):
def display(self):
print('Current value = "%s"' % self.data )
z = SecondClass()
z.setdata(42)
z.display()
Current value = "42"
x.display() # 子类SecondClass的专有化完全是在FristClass外部完成的,故子类不会影响当前或未来的FirstClass对象
New Value
类知识文件内的语句
导入模块,从模块中引用类class
from keras.layers import Dense
class MyDense1(Dense):
def display(self):
print('Learning Python!')
import keras.layers
class MyDense2(Dense):
def display(self):
print('Learning Python!')
# food.py
var = 1
def func():
...
class spam:
...
class ham:
...
class eggs:
...
class person:
...
import persom # Import module
x = person.person() # class within module
import person
x = person.Person()
运算符可让类与Python的对象模型相集成
运算符重载一般给开发人员用,所以一般少用;除非”init方法”,也就是构造函数方法,它是用于初始化对象状态的。
class ThirdClass(SecondClass): # Inherit from SecondClass
def __init__(self,value): # On "ThirdClass(value)"
self.data = value
def __add__(self,other): # On "self+other"
return ThirdClass(self.data+other) # 创建返回新对象,未修改
def __str__(self): # On "print(self),"str()"
return '[ThirdClass:%s]' %self.data
def mul(self,other): # In-place change:named
self.data *= other # 修改了self对象的值
a = ThirdClass('abc') # __init__ called
a.display()
print(a)
Current value = "abc"
[ThirdClass:abc]
b = a+'xyz'
b.display()
print(b)
Current value = "abcxyz"
[ThirdClass:abcxyz]
a.mul(3)
print(a)
[ThirdClass:abcabcabc]
几乎每个实际的类似乎都会出现一个重载方法:__init__构造函数。因为这可以让类立即在其新建的实例内添加属性。
class rec:pass
rec.name = 'Bob'
rec.age = 40
help(rec)
Help on class rec in module __main__:
class rec(builtins.object)
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| age = 40
|
| name = 'Bob'
x = rec()
y = rec()
x.name, y.name # name is stored on the class only
('Bob', 'Bob')
赋值操作为对象开辟了新的属性空间,不影响其他对象的继承搜索
x.name = 'Sue' # But assignment changes x only
rec.name, x.name, y.name
('Bob', 'Sue', 'Bob')
命名空间对象的属性通常都是以字典的形式实现的,__dict__属性是针对大多数基于类的对象的命名空间字典
rec.__dict__.keys()
dict_keys(['__module__', '__dict__', '__weakref__', '__doc__', 'name', 'age'])
print(list(x.__dict__.keys())) # x有自己的命名空间name
print(list(y.__dict__.keys())) # y继承搜索rec命名空间中的name,本身不具有name命名空间
['name']
[]
print(x.__class__)
print(rec.__bases__)
(,)
def upperName(self):
return self.name.upper() ## still needs a self
upperName(x)
'SUE'
rec.method = upperName
print(x.method()) # run method to process x
print(y.method()) # same, but pass y to self
print(rec.method(x)) # Can call through instance or class
SUE
BOB
SUE
Python中的OOP其实就是在已连接命名空间对象内寻找属性而已
字典
rec = {}
rec['name']='mel'
rec['age']=45
rec['job']='trainer/writer'
print(rec['name'])
mel
类
class rec:pass
rec.name = 'mel'
rec.age = 45
rec.job = 'trainer/writer'
print(rec.name)
mel
我们产生一个空类的实例来表示每条不同的记录
class rec:pass
pers1 = rec() # an empty class
pers1.name = 'mel'
pers1.job = 'trainer'
pers1.age = '40'
pers2 = rec() # an empty class
pers2.name = 'vls'
pers2.job = 'developer'
pers1.name,pers2.name
('mel', 'vls')
最后,我们可能编写一个更完整的类来实现记录及其处理
class Person:
def __init__(self,name,job):
self.name = name
self.job = job
def info(self):
return (self.name,self.job)
rec1 = Person('mel','trainer')
rec2 = Person('vsl','developer')
rec1.job,rec2.info()
('trainer', ('vsl', 'developer'))