如何从另一个类继承变量



我有一个代码:

class read:
a = 0
c = write.c
def get_num():
a = 6
return a

class write:
c = 0 
a = read.get_num()
def do_num(self):
b = read.get_num()
self.c = 10
return b
print(write.c)

问题:

  1. 如何在最后获得print(write.c)的解决方案10c
  2. 如何使行3中的变量c等于类write中的c = 0
  3. 如何使行3中的可变c等于类write中的c = 10
  1. do_num()需要设置write.c而不是self.c,以便设置类属性而不是实例属性。你需要打电话给no_num().
class write:
c = 0 
a = read.get_num()
def do_num(self):
b = read.get_num()
write.c = 10
return b
w = write()
w.do_num()
print(write.c)
  1. 您需要按其他顺序定义类。在定义类之前,无法访问write.c
class write:
c = 0 
a = read.get_num()
def do_num(self):
b = read.get_num()
write.c = 10
return b
class read:
a = 0
c = write.c
def get_num():
a = 6
return a
  1. 您需要read.c创建一个类属性,该属性在每次使用时读取write.c的值。请参阅如何创建类属性?了解如何定义类属性。

你应该在这里考虑两件事,我强烈建议你仔细看看python中的继承,因为这正是你正在寻找的。永远记住坚持传统的命名模式,因此你的类应该大写

class Write:
c = 0 
def do_num(self):
b = read.get_num()
self.c = 10
return b
class Read:
a = 0
c = Write.c
def get_num():
a = 6
return a

这是行不通的,因为在每个回合你都会尝试引用一个不存在的类,这意味着当你创建类时,你的代码中的内容Write你引用了尚未被克雷塔化的Read类,如果你切换它,你就会遇到完全相同的问题。

话虽如此,我相信更适合您在这里尝试完成的工作是使用类属性而不是类变量

class Book:
def __init__(self, a, c):
self.c = c
self.a = a
def do_num(self):
#some code
def do_num(self):
#some code
write = Book(0, 10) #a=0 and c=10
read = Book(10, 0) #a=10 and c=0

有了这个,您可以拥有 A 和 C 的各种实例和变体,而不会不必要地纠缠在继承网络中。而且由于您尝试在两个类中使用相同的变量和方法,因此没有理由不将其设置为一个类并使用该类的实例

最新更新