时间:2022-10-27 10:45:42 | 栏目:Python代码 | 点击:次
格式:class 类名[(父类)]:
#两种方式意思相同 class Person: pass class Person(object): pass
name、age、subject就是类属性
class Student: #类属性 name = '' age = 0 subject = []
格式: def 方法名(self[,parm1,parm2...]): pass
self就是对象本身
class Student: # 类属性 name = 'student' age = 0 subject = [] # 普通方法 def study(self): print(self.name, '正在学习...') xiaoming = Student() xiaoming.name = 'xiaoming' xiaoming.study()
------------
输出:
xiaoming 正在学习...
class Student: # 类属性 name = 'student' age = 0 subject = [] # 普通方法 def study(self, name): print(name, '正在学习...') s1 = Student() s1.study('xiaohong')
----------------
输出:
xiaohong 正在学习...
格式: @classmethod def 方法名(cls): pass
class Dog: dog_type = '阿拉斯加' def __init__(self, nickname): self.name = nickname def dog_run(self): print('{}在公园里跑.看起来是一只{}.'.format(self.name, self.dog_type)) @classmethod def dog_sit(cls): print(cls.dog_type, '很乖,坐下了') dog1 = Dog('肉丸') dog1.dog_type = '小泰迪' dog1.dog_run() Dog.dog_sit()
--------------
输出:
肉丸在公园里跑.看起来是一只小泰迪.
阿拉斯加 很乖,坐下了
class Dog: def __init__(self, nickname): self.name = nickname @staticmethod def dog_sit(): print('很乖,坐下了') dog1 = Dog('肉丸') dog1.dog_sit() Dog.dog_sit() ---------------------
输出:
很乖,坐下了
很乖,坐下了
格式: def __方法名__(self): pass
__init__() 构造函数
格式:对象名 = 类名()
class Student: #类属性 name = '' age = 0 subject = [] xiaoming = Student()
class Student: # 类属性 name = 'student' age = 0 subject = [] xiaoming = Student() print('类属性:', xiaoming.name) # 此时是从类中获取的类属性 xiaoming.name = 'xiaoming' # 因为赋值了,此时变成了对象属性 print('对象属性:', xiaoming.name) -------------
输出:
类属性: student
对象属性: xiaoming