创建一个Address类

时间:2017-03-22 18:26:31

标签: python class

我在理解课程时遇到了很大的问题。我必须使用实例变量创建一个地址类:street,city,state和zipcode然后我必须添加一个__str__方法,该方法返回一个打印实例变量的字符串。

对不起!这是我现在的代码 我的问题是试图打印实例变量,因为现在它们是未定义的。

class Address:

def __init__(self, street, city, state, zipcode):
    self.street = street
    self.city = city
    self.state = state
    self.zipcode = zipcode

def get_street(self, street):
    return self.street

def get_city(self, city):
    return self.city

def get_state(self, state):
    return self.state

def get_zipcode(self, zipcode):
    return self.zipcode

def __str__(self):
    return str(self.street,self.city,self.state,self.zipcode)

street = Address(Grandview)
street.get_street
city = Address(Westland)
city.get_city
state = Address(Michigan)
state.get_state
zipcode = Address(48186)
zipcode.get_zipcode
print(street, city, state, zipcode)

2 个答案:

答案 0 :(得分:0)

您已将class __init__(...)定义为传递4 arguments

def __init__(self, street, city, state, zipcode):  

但只传递一个未定义Grandview

street = Address(Grandview)

您已定义,例如get_street(...)作为一项功能:

def get_street(self, street):
return self.street

但将其用作class attribute

street.get_street

我建议阅读: python-websites-tutorials

答案 1 :(得分:0)

根据您的代码,它应该是:

class Address:

    def __init__(self, street, city, state, zipcode):
        self.street = street
        self.city = city
        self.state = state
        self.zipcode = zipcode

    def get_street(self, street):
        return self.street

    def get_city(self, city):
        return self.city

    def get_state(self, state):
        return self.state

    def get_zipcode(self, zipcode):
        return self.zipcode

    def __str__(self):
        return str(self.street,self.city,self.state,self.zipcode)

address = Address('Grandview', 'Westland', 'Michigan', 48186)
street = address.get_street()
city = address.get_city()
state = address.get_state()
zipcode = address.get_zipcode()

print "%s, %s, %s, %s" % (street, city, state, zipcode)