#类
#定义 class myclass:
class my_class:
num = 0 #成员, 一般为公共属性
def func(self): #类方法, 函数
return 'hello world'
cl = my_class() #实例化
print(cl.func(), cl.num) #hello world
# _init_() 构造方法
class my_class1:
def __init__(self, a, b): #相当于构造函数
self.val1 = a
self.val2 = b
print('--------')
x = my_class1(2, 3)
print(x.val1, x.val2) # 2 3
'''
--------
2 3
'''
class test:
def print_self(self):
print(self)
# print(self._class_)
t = test()
t.print_self() #<__main__.test object at 0x000002071F3E8790> , 对象地址
#self 代表的是累的实例, 是一个对象
#类方法, 即在类中定义函数
class people:
def __init__(self, name, age, weight):
self.name = name
self.age = age
self.weight = weight
def say_hello(self):
print('大家好, 我是{}, 今年{} 岁了, 体重 {} 千克'.format(self.name, self.age, self.weight))
p = people('法外狂徒张三', 23, 67)
p.say_hello() #大家好, 我是法外狂徒张三, 今年23 岁了, 体重 67 千克
#类的继承
class stud(people):
grad = ''
def __init__(self, n, a, w, g):
people.__init__(self, n, a, w)
self.grad = g
def say(self):
print('大家好, 我是{}, 今年{} 岁了, 体重 {} 千克, 读{}年级'.format(self.name, self.age, self.weight, self.grad))
s = stud('李四', 12, 45, 6)
s.say() #大家好, 我是李四, 今年12 岁了, 体重 45 千克, 读6年级
#类的方法重写
class parent:
def my_method(self):
print('father')
class child(parent):
def my_method(self):
print('child_own')
c = child()
c.my_method() #直接调用类内的方法
super(child, c).my_method() #super 用来调用父类的方法
'''
child_own
father
'''
#类的属性与方法
#类的私有属性, _private_attrs
#类的私有方法, _private_method
class counter:
public_count = 0
_privatec_count = 0
def count(self):
self.public_count += 1
self._privatec_count += 1
c = counter()
c.count()
c.count()
print(c.public_count) #2, 私有属性, 外部成员无法访问
class site:
def __init__(self, name, url):
self.name = name
self.url = url
def who(self):
print('name :', self.name)
print('url : ', self.url)
def _private(self): #私有方法外部成员无法访问
print('私有方法')
def public(self):
print('公共方法')
print(' ------- ')
self._private()
print('---------')
st = site('taobao', 'hahah.com')
st.who()
st.public()
'''
name : taobao
url : hahah.com
公共方法
-------
私有方法
---------
'''
#python 还有专有方法, 可自定义实现, 需要前面加 __
class my_oper:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def get_vlaue(self):
print('a = {}, b = {}, c = {}'.format(self.a, self.b, self.c))
def __add__(self, other):
new_a = self.a + other.a
new_b = self.b + other.b
new_c = self.c + other.c
return my_oper(new_a, new_b, new_c)
def __sub__(self, other):
new_a = self.a - other.a
new_b = self.b - other.b
new_c = self.c - other.c
return my_oper(new_a, new_b, new_c)
def __mul__(self, other):
new_a = self.a * other.a
new_b = self.b * other.b
new_c = self.c * other.c
return my_oper(new_a, new_b, new_c)
def __divmod__(self, other):
new_a = self.a / other.a
new_b = self.b / other.b
new_c = self.c / other.c
return my_oper(new_a, new_b, new_c)