首先,我也不知道是不是python 中有类变量这个东西,不过叫不叫这个不重要,不过是一个文字游戏,关键是它的行为是什么。
class One:
def __init__(self):
self.one = 1
self.two = 2
def printnum(self, num):
if num == 1:
print(self.one)
elif num == 2:
print(self.two)
class test:
one=One()
def __init__(self,num):
self.one.printnum(num)
if __name__ == "__main__":
t = test(1)
不叫self 调用
class One:
def __init__(self):
self.one = 1
self.two = 2
def printnum(self, num):
if num == 1:
print(self.one)
elif num == 2:
print(self.two)
class test:
one=One()
def __init__(self,num):
self.one.printnum(num)
def print2(self,num):
one.printnum(num)
if __name__ == "__main__":
t = test(1)
t.print2(1)
在方法中,重新使用个名字 self.tow 去调用
class One:
def __init__(self):
self.one = 1
self.two = 2
def printnum(self, num):
if num == 1:
print(self.one)
elif num == 2:
print(self.two)
class test:
one=One()
def __init__(self,num):
self.one.printnum(num)
def print2(self,num):
self.two.printnum(num)
if __name__ == "__main__":
t = test(1)
t.print2(1)
在test类中,直接修改One 中属性值,查看是否会改变
class One:
def __init__(self):
self.one = 1
self.two = 2
def printnum(self, num):
if num == 1:
print(self.one)
elif num == 2:
print(self.two)
class test:
one=One()
def __init__(self,num):
self.one.printnum(num)
def print2(self,num):
self.one.one =2
self.one.printnum(num)
if __name__ == "__main__":
t = test(1)
t.print2(1)
那再次新建一个test的实例,查看修改是否能在两个test实例访问
class One:
def __init__(self):
self.one = 1
self.two = 2
def printnum(self, num):
if num == 1:
print(self.one)
elif num == 2:
print(self.two)
class test:
one=One()
def __init__(self,num):
self.one.printnum(num)
def print2(self,num):
self.one.one =2
self.one.printnum(num)
if __name__ == "__main__":
t = test(1)
t.print2(1)
t2 = test(1)
- 结果是的,可以在两个不同的实例之间访问
新建一个新的类,也包含一个python中的类变量,查看修改能够访问
class One:
def __init__(self):
self.one = 1
self.two = 2
def printnum(self, num):
if num == 1:
print(self.one)
elif num == 2:
print(self.two)
class test:
one=One()
def __init__(self,num):
self.one.printnum(num)
def print2(self,num):
self.one.one =2
self.one.printnum(num)
class test2:
one=One()
def __init__(self,num):
self.one.printnum(num)
def print2(self,num):
self.one.one =2
self.one.printnum(num)
if __name__ == "__main__":
t = test(1)
t.print2(1)
t2 = test(1)
t3 = test2(1)
- 结果的话,这次的修改毫无疑问是无法访问
希望大家能够知道,一个事物,叫什么不过是一个文字游戏,重要的是有什么特点,与现有的事物有啥异同。
|