# 面向过程编程 s = "alexdsb" count = 0 for i in s: count += 1 print(count) s = [1,2,7,3,4,5,] count = 0 for i in s: count += 1 print(count) # 面向对象编程 def my_len(s): count = 0 for i in s: count += 1 print(count) my_len([1,2,3,4,5])
可得出结论:
# 面向函数编程 def login(): pass def check_buy_goods(): pass def change_pwd(): pass def shopping(): pass def register(): pass def check_unbuy_goods(): pass # 面向对象编程 class Auth: def login(self): pass def register(self): pass def change_pwd(self): pass class Shopping: def shopping(self): pass def check_buy_goods(self): pass def check_unbuy_goods(self): pass
可以得出结论:
class People: mind = "有思想" # 静态属性 def eat(self): # 方法 print("在吃饭") def work(self): print("在工作") class Dog: hair = "ë" # 静态属性 def eat(self): print("吃食") def lick(self): print("添水")
class People: mind = "有思想" # 静态属性 def eat(self): # 方法 print("在吃饭") def work(self): print("在工作")
print(People.__dict__) # __dict__ 只能查看当前空间下的内容
print(People.mind) # 类名.属性名
一般情况我们不使用类名去操作方法(类方法)
People.emotion = "有情感"
(4)删:
del People.mind
People.mind = "无脑"
print(People.mind) #类名.属性名 单独查一个 print(People.__dict__) # 查看类下所有的
class People: mind = "有思想" # 静态属性 def eat(self): # 方法 print("self --->",self) print("在吃饭") def work(self): print("在工作") # 创建对象 -- 类名() p = People() # 实例化对象 print(p.__dict__) # 对象的空间 print("p---->",p) print(p.mind) p.eat() p.work()
class People: mind = "有思想" # 静态属性 def __init__(self,name,age,sex): # 初始化 # self == p self.name = name self.age = age self.sex = sex def eat(self): # 方法 print(self.name) print("在吃饭") def work(self): print("在工作") p = People("marry",19,"男") # 实例化一个对象 p.eat()
可以在类的外部给对象创建属性,但不建议这样使用
p.mind = "无脑" # 给对象创了一个属性 print(People.__dict__) print(p.__dict__) # 对象查询对象中所有属性
class People: mind = "有思想" # 静态属性 def __init__(self,name,age,sex,high=None): # 初始化(给创建的对象封装独有属性) # self == p 地址相同 self.name = name self.age = age self.sex = sex if high: self.high = high def eat(self): # 方法 print(f"{self.name}在吃饭") def work(self): print("在工作") p1 = People("jim",19,"δ֪",170) # 实例化一个对象 p2 = People("kuqir",19,"δ֪",170) # 实例化一个对象 p3 = People("diva",19,"δ֪",170) # 实例化一个对象 p4 = People("李玲",19,"δ֪",170) # 实例化一个对象 p5 = People("好哥",19,"δ֪",170) # 实例化一个对象 p1.eat() p2.eat()
class A: def __init__(self,name): # 类里边给对象添加属性 self.name = name def func(self,sex): self.sex = sex a = A("jim") a.func("男") # 类外边给对象添加属性 a.age = 18 print(a.__dict__) # 总结:给对象空间添加属性可以在类的内部,类的外部,类中的方法
class A: def __init__(self,name): # 类内部给类空间添加属性 A.name = name def func(self,age): # 类中的方法给类空间添加属性 A.age = age 类外部给类空间添加属性 A.name = "alex" a = A('meet') a.func(19) print(A.__dict__) # 总结:给类空间添加属性可以在类的内部,类的外部,类中的方法
来源:博客园
作者:永亮
链接:https://www.cnblogs.com/caiyongliang/p/11572034.html