如何从外部函数向不是__init__
的方法添加属性。
例如
class Year:
def __init__(self):
self._list = []
def add_year(self,year):
self._year = year
self._list.append(self._year)
def main():
year = 1998
#how do I get this year into the year class to add to list?
答案 0 :(得分:3)
如上面的评论所述:
创建实例:
yobj = Year()
并传递要分配的值
year = 1998
yobj.add_year(year)
答案 1 :(得分:0)
方法__init__
除了在实例化对象时执行外没有什么特别的。这意味着,您可以在代码中的几乎任何地方(不仅在Year
中,为__init__
的实例分配或获取属性。
class Year:
def __init__(self):
# You can define an attribute in __init__
self.year_list = []
def add_year(self, year):
# You can define and access an attribute in any method
self.last_year_added = year
self.year_list.append(year)
def main():
year = 1998
# You must instantiate a Year first
my_year = Year()
# Then execute the method add_year
my_year.add_year(year)
my_year.add_year(year + 1)
print(my_year.year_list) # [1998, 1999]
print(my_year.last_year_added) # 1999
# Note that you can even add attribute outside methods
my_year.month = 'December'
print(my_year.month) # December
main()
答案 2 :(得分:-1)
下面是一个例子,看看是否有帮助
class Dog:
# Class Attribute
species = 'mammal'
# Initializer / Instance Attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def description(self):
return "{} is {} years old".format(self.name, self.age)
# instance method
def speak(self, sound):
return "{} says {}".format(self.name, sound)
# Instantiate the Dog object
mikey = Dog("Mikey", 6)
# call our instance methods
print(mikey.description())
print(mikey.speak("Gruff Gruff"))
输出如下。
Mikey is 6 years old
Mikey says Gruff Gruff
如果您想了解有关使用python进行面向对象的方式编程的更多信息,请遵循以下教程-[https://realpython.com/python3-object-oriented-programming/][1]