I have a code:
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)
Questions:
print(write.c)
at the end 10
for c
.c
in line 3
equal to the c = 0
in class write
c
in line 3
equal to the c = 10
in class write
do_num()
needs to set write.c
rather than self.c
so that it sets the class attribute rather than an instance attribute. And you need to call 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)
write.c
before the class is defined.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
read.c
a class property that reads the value of write.c
whenever it's used. See How to make a class property? for how to define a class property.Two things you should consider here, I strongly recommend you take a close look at inheritance in python cause that is exactly what you are looking for. Always remember to stick to conventional naming patterns, hence your classes should be capitalized
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
This will not work because on every turn you will be trying to reference a non existent class, meaning that what you have in your code, when you create class Write
you reference the Read
class which has not be cretaed yet and if you switch it up you have the exact same problem.
With that said i believe what would be a better fit for what you are trying to accomplish here would be using class attributes not class variables
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
with this you can have various instances and variations of a and c without getting tangled in a web of inheritance needlessly. And since you are trying to work with the same variables and methods in both classes, there is no reason not to make it one class and use instances of that class instead
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.