我有我的商務類的實例列表。我習慣於在類的頂部定義一個類的變量。 Business類中的變量是一個標籤列表。當我瀏覽商家名單時,有些商店有標籤,有些則沒有。在20個企業中,列表中的第4個元素有4個標籤。在將這些標籤添加到此業務後,所有以下Business的實例也會共享這些標籤。這是我的講座Python中的全局變量?
from tag import *
class Business:
name = ""
website = ""
phone = ""
address = ""
city = ""
state = ""
postalCode = ""
tags = []
data = {}
def __init__(self, name):
self.setName(name)
# Modifiers
def setName(self, name):
self.name = name
def setWebsite(self, website):
self.website = website
def setPhone(self, phone):
self.phone = phone
def addTag(self, Tag):
self.tags.append(Tag)
def setAddress(self, address):
self.address = address
def setCity(self, city):
self.city = city
def setState(self, state):
self.state = state
def setPostalCode(self, postalCode):
self.postalCode = postalCode
def set(self, key, value):
self.data[key] = value
def unset(self, key):
del self.data[key]
# Accessors
def getWebsite(self):
return self.website
def getName(self):
return self.name
def getPhone(self):
return self.phone
def getTags(self):
return self.tags
def getAddress(self):
return self.address
def getCity(self):
return self.city
def getState(self):
return self.state
def getPostalCode(self):
return self.postalCode
def get(self, key):
return self.data[key]
def getKeys(self):
return self.data.keys()
# Helpers
和標籤被添加到一個企業就像這個 -
if len(categories) > 1:
for cat in categories:
B.addTag(Tag(cat))
在我的商業類的全球商務的所有實例的頂部定義的變量?我該如何解決這個問題?
這是一個非常普遍的問題。請參閱[此處](http://stackoverflow.com/a/15489578/748858)以獲取解釋。 – mgilson
或者,[這裏](http://stackoverflow.com/q/13070948/748858)是另一個。 – mgilson
而這一個:http://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes –