本章我们来关注一下Python中的类与对象:
1.最基本的类结构
class Cdict:
def getkeys(self,dicts):
keys=[]
for k in dicts:
keys.append(k)
return keys
def getvals(self,dicts):
vals=[]
for k in dicts:
vals.append(dicts[k])
return vals
dicts={'name':'user1','age':20}
#从类中实例化对象
obj=Cdict
r=obj.getkeys(obj,dicts)
print(r)
r2=obj.getvals(obj,dicts)
print(r2)
2.默认参数
class Person:
def _init_(self,name='user1'):
self.name=name
self.age=20
def say(self):
print(self.name,self.age)
obj=Person()
obj.say()
3.默认属性
def Person:
def _init_(self,name):
self.name=name
self.age=20
def say(self):
print(self.name,self.age)
obj=Person('user1')
obj.say()
4.类中方法的分类
class Cdict:
def _init_(sellf,dicts):
self.dicts=dicts
self.keys=[]
self.vals=[]
def getkeys(self):
self.key=[]
for k in self.dicts:
self.dicts.append(k)
return self.keys
def getvals(self):
self.vals=[]
for k in self.dicts:
self.vals.append(dicts[k])
return self.vals
def sum(self,i,j):
return i+j
dicts={'name':'user1','age':20}
# 从类中实例化对象
obj=Cdict(dicts)
s=obj.sum(1,3)
print(s)
5.一个类使用另一个类
class Person:
def __init__(self,name):
self.name=name
def say(self):
return f'my name is {self.name}'
class Sub:
def __init__(self,age):
self.age=age
def eat(self):
x=Person('user1')
z=x.say()
y=Sub(20)
y.eat()
6.类继承
class Person:
def __init__(self,name='user1'):
self.name=name
self.age=20
def say(self):
print(self.name,self.age)
class Sub(Person):
pass
obj=Sub()
obj.say()
7.类继承重载
class Person:
def _init_(self,name):
self.name=name
def say(self):
print(self.name)
class Sub(Person):
def _init_(self,name,age):
super()._init_(name)
self.age=age
def say(self):
print(self.name,self.age)
obj=Sub('user1',20)
obj.say()
8.将实例用作属性
class Person:
def __init__(self,name):
self.name=name
def say(self):
return f'my name is {self.name}'
class Sub:
def __init__(self,age):
self.age=age
self.per=Person('user1')
y=Sub(20)
print(y.per.say())
9.最后我们来一个完整的处理字典类Cdict
class Cdict:
def __init__(self,dicts):
self.keys=[]
self.vals=[]
self.dicts=dicts
def getkeys(self):
self.keys=[]
for k in self.dicts:
self.keys.append(k)
return self.keys
def getvals(self):
for k in self.dicts:
self.vals.append(self.dicts[k])
return self.vals
dicts={'name':'user1','age':20}
obj=Cdict(dicts)
keys=obj.getkeys()
print(keys)
vals=obj.getvals()
print(vals)
?可供初学者参考,我们下期再见!
|