我想从函数中将类对象(Yuman(附加到全局列表中,但收到错误:
发生异常:TypeError"Yuman"对象不可调用
只有当append在该特定函数中时,当相同类型的append在不同的更简单函数中工作时,才会发生异常(更简单的函数在底部(。
import dataclasses
import random
yumanList: list = [] # for storing Yuman objects.
'''a crude simulation of 2x2 Mendelian trait inheritance'''
@dataclasses.dataclass
class Yuman: # !!! THE CLASS IN QUESTION !!!
Trait: str # GG, Gg, gG, gg.
Sex: int # 1 is Male, 2 is Female.
Breeded: bool
def reproduce() -> None:
global Yuman
# establishes all variables to be blank slates...
_daddyTrait: str = "Unassigned"
_mommyTrait: str = "Unassigned"
_traitPool: list = [] # list of both daddy and mommy letter traits
_childAmount: int = 0
# picks a random number used for indexing the _traitPool list.
def _traitNumber() -> int:
return random.randint(0, 3)
# combines 2 separate indexed values from _traitPool.
def _traitAssigner() -> str:
_traitProduct: str = _traitPool[(
_traitNumber())] + _traitPool[(_traitNumber())]
return _traitProduct # the combined 2 string values as 1 string value.
# gets a trait from the male Yuman and adds to _daddyTrait.
while (_daddyTrait == "Unassigned"):
for Yuman in yumanList:
if Yuman.Breeded == False:
if Yuman.Sex == 1:
_daddyTrait: str = Yuman.Trait
Yuman.Breeded = True
# gets a trait from a female Yuman and adds to _mommyTrait.
while (_mommyTrait == "Unassigned"):
for Yuman in yumanList:
if Yuman.Breeded == False:
if Yuman.Sex == 2:
_mommyTrait: str = Yuman.Trait
Yuman.Breeded = True
for letter in _daddyTrait: # adds daddy trait attributes to the pool...
_traitPool.append(letter)
for letter in _mommyTrait: # adds mommy trait attributes to the pool...
_traitPool.append(letter)
random.shuffle(_traitPool) # shuffles the pool
# determines the amount of children to be born in _childAmount...
_childAmount: int = random.randint(1, 7)
for i in range(_childAmount): # !!! PROBLEM HERE !!!
yumanList.append(
Yuman(_traitAssigner(), (random.randint(1, 2)), False))
# !!Exception has occurred: TypeError 'Yuman' object is not callable!!
# !!! SIMILAR FUNCTION BUT NO PROBLEM!!! appending the initial 20 Yuman objects to yumanList...
for i in range(20):
yumanList.append(Yuman("Gg", (random.randint(1, 2)), False))
while True:
reproduce()
我尝试创建一个中间的局部变量,比如:
global Yuman
_yuman = Yuman
但它不起作用。
我在函数中将Yuman定义为全局的,而不是全局的,但两者都不会影响问题。我还试图将append限制在函数本身的子函数中,然后调用子函数,但这也不起作用。
在循环中:
for Yuman in yumanList:
循环变量称为Yuman
(与类名相同!(。请选择另一个名称,这样Yuman
就不会被覆盖。
从本质上讲,在循环之后,变量Yuman
不再指向类,而是指向循环中迭代的最后一个项。快速示例:
>>> s = 'I am a string.'
>>> for s in '123': #notice, same variable name as the string above
... print(s)
...
1
2
3
>>> s
'3'
修复方法是,再次将循环变量重命名为其他变量:
>>> s = 'I am a string.'
>>> for a in '123': #diff. variable name from above
... print(a)
...
1
2
3
>>> s
'I am a string.'