[英]How can I reference variable in different functions?
class Person:
def __init__(self, name, address, phone):
self.name = name
self.address = address
self.phone = phone
def set_name(self, name):
self.name = name
def set_address(self, address):
self.address = address
def set_phone(self, phone):
self.phone = phone
def get_name(self):
return self.name
def get_address(self):
return self.address
def get_phone(self):
return self.phone
class Customer:
def __init__(self, number, mail):
self.number = number
self.mailing_list = mail
def set_number(self, number):
self.number = number
def set_mailinglist(self, mail):
self.mailing_list = mail
def get_number(self):
return self.number
def get_mailinglist(self):
if m == 'Y' or m == 'y':
self.mailing_list = 'Yes'
elif m =='N' or m =='n':
self.mailing_list = 'No'
return self.mailing_list
def main():
me = Person(name= n , address = a, phone = p)
n = input('Enter Customer Name: ')
a = input('Enter Customer Address: ')
p = input('Enter Customer Phone Number: ')
print('Customer Name:', me.name)
print('Customer Address:', me.address)
print('Customer Phone Number:', me.phone)
me1 = Customer(number= nu, mail = m)
nu = int(input('Enter Customer Number: '))
m = input('Add Customer to Mailing List [Y/N]?: ')
print('Customer Number:', me1.number)
print('Customer Mailing List:', me1.mailing_list)
main()
I want to make it where it'll print what the user answers in the input along with the other stuff.我想让它打印用户在输入中回答的内容以及其他内容。 How am I able to get the variables I have in main to pass through the functions I have?我怎样才能让我在main中拥有的变量通过我拥有的函数? If there are any other mistakes I have made that I didn't notice, please let me know as I learn best on what was wrong and how to fix them.如果我犯了任何其他我没有注意到的错误,请告诉我,因为我最了解错误以及如何解决这些错误。
The reason for the behavior seen is:所见行为的原因是:
You have created an object of Person
well before without taking the input.在没有输入之前,您已经创建了Person
的 object。
Same for the obj of type Customer
. Customer
类型的 obj 也是如此。
As you are creating object before taking the inputs, the values assigned to the member variables are None
.当您在获取输入之前创建 object 时,分配给成员变量的值为None
。 I have updated your function main
by putting the code to create object of Person
and Customer
at right places and now it will work as expected.我已经更新了您的 function main
文件,方法是在正确的位置放置创建Person
和Customer
的 object 的代码,现在它将按预期工作。
def main():
n = input('Enter Customer Name: ')
a = input('Enter Customer Address: ')
p = input('Enter Customer Phone Number: ')
me = Person(name= n , address = a, phone = p) # the right place to create obj
print('Customer Name:', me.name)
print('Customer Address:', me.address)
print('Customer Phone Number:', me.phone)
nu = int(input('Enter Customer Number: '))
m = input('Add Customer to Mailing List [Y/N]?: ')
me1 = Customer(number= nu, mail = m) # right place to create object
print('Customer Number:', me1.number)
print('Customer Mailing List:', me1.mailing_list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.