我收到错误:
NameError: name 'OrgUnit' is not defined
Run Code Online (Sandbox Code Playgroud)
class OrgUnit(object):
def __init__(self,
an_org_name: str,
its_parent_org_unit: OrgUnit= None
):
self.org_unit_name = an_org_name
self.parent_org_unit = its_parent_org_unit
def __str__(self):
if self.parent_org_unit:
parent_org_unit_name = self.parent_org_unit.__str__()
return parent_org_unit_name + "->" + self.org_unit_name
else:
return self.org_unit_name
if __name__ == '__main__':
ibm_worldwide = OrgUnit("IBM_Worldwide")
ibm_usa = OrgUnit("IBM_USA", ibm_worldwide)
ibm_asia = OrgUnit("IBM_Asia", ibm_worldwide)
ibm_china = OrgUnit("IBM_China", ibm_asia)
print(ibm_worldwide)
print(ibm_usa)
print(ibm_asia)
print(ibm_china)
Run Code Online (Sandbox Code Playgroud)
我确信这是一个已知的范例,因为它似乎是一个非常常见的分层类使用问题(自引用类).我知道我可以改变的类型its_parent_org_unit是object和它的作品,但是这似乎是错误的做法,主要是因为它泄水我检查类型的我的电话的能力.随着its_parent_org_unit改变是一种类型的object我得到正确的结果:
IBM_Worldwide
IBM_Worldwide->IBM_USA
IBM_Worldwide->IBM_Asia
IBM_Worldwide->IBM_Asia->IBM_China
Run Code Online (Sandbox Code Playgroud)
我对这些想法和建议持开放态度.做这种事情最"pythonic"的方法是什么?
PS:这种"自引用类"范例/问题的名称是什么,我可以用来查找其他建议?
在Python 3.5中,添加了类型注释(参见此处).
有没有一种定义递归类型注释的方法,例如树状结构?
class Employee(object):
def __init__(self, name: str, reports: List[Employee]):
self.name = name
self.reports = reports
Run Code Online (Sandbox Code Playgroud)
在上面,似乎注释不起作用List[Employee].运行代码会导致此错误:
NameError: name 'Employee' is not defined
我试图找出类型的自引用如何与python3的类型注释一起工作 - 文档没有指定任何关于此的内容.
举个例子:
from typing import TypeVar, Optional, Generic
T = TypeVar('T')
class Node(Generic[T]):
left = None
right = None
value = None
def __init__(
self, value: Optional[T],
left: Optional[Node[T]]=None,
right: Optional[Node[T]]=None,
) -> None:
self.value = value
self.left = left
self.right = right
Run Code Online (Sandbox Code Playgroud)
此代码生成错误:
Traceback (most recent call last):
File "node.py", line 4, in <module>
class Node(Generic[T]):
File "node.py", line 12, in Node
right: Optional[Node[T]]=None,
NameError: name 'Node' is not defined
Run Code Online (Sandbox Code Playgroud)
这是使用Python 3.5.1
如何键入返回实例对象的静态方法?
import typing
class foo(object):
@staticmethod
def getOne() -> foo:
return FooRegister().get()
Run Code Online (Sandbox Code Playgroud)
FooRegister包含 的所有实例foo。但是,如果我按所示输入它,python 会抱怨,因为foo尚未定义。
键入此内容的正确方法是什么?
为什么说它找不到我的课?为什么我要创建另一个具有相同名称的类,以使其不抱怨?
from typing import Dict
class WeekDay:
def __init__(self, day_number, day_name):
self.day_name = day_name
self.day_number = day_number
@staticmethod
def get_week_days() -> Dict[str, WeekDay]: # WeekDay unresolved reference error
weekdays = {
"monday": WeekDay(1, "Monday"),
"tuesday": WeekDay(2, "Tuesday"),
"wednesday": WeekDay(3, "Wednesday"),
"thursday": WeekDay(4, "Thursday"),
"friday": WeekDay(5, "Friday"),
"saturday": WeekDay(6, "Saturday"),
"sunday": WeekDay(7, "Sunday")
}
return weekdays
Run Code Online (Sandbox Code Playgroud) 问题是这样的:
class A():
def foo() -> B:
pass
class B():
def bar() -> A:
pass
Run Code Online (Sandbox Code Playgroud)
这将引发一个NameError: name 'B' is not defined.
为了进行类型检查,我不愿意更改-> B为-> "B". 有什么解决方法吗?
我有一个看起来像这样的课程:
class CareerTransition(object):
def __init__(self, title_from: str, title_to: str)->None:
self.title_from = title_from # type: str
self.title_to = title_to # type: str
@staticmethod
def from_file(fname: str, verbose : bool = False)->List[CareerTransition]:
#Do some stuff
pass
Run Code Online (Sandbox Code Playgroud)
当我尝试实例化该类时,我收到此错误:
Traceback (most recent call last):
File "/Users/simon.hughes/GitHub/analytics-py-careerpathing/careerpathing/data/employment_history.py", line 8, in <module>
class CareerTransition(object):
File "/Users/simon.hughes/GitHub/analytics-py-careerpathing/careerpathing/data/employment_history.py", line 17, in CareerTransition
def from_file(fname: str, verbose : bool = False)->List[CareerTransition]:
NameError: name 'CareerTransition' is not defined
Run Code Online (Sandbox Code Playgroud)
是否不可能使用类型注释来引用引用当前类的泛型类型?澄清(因为它可能不是很明显)它正在抛出该错误,因为该类尚未定义.有没有解决的办法?
给定一个具有一些受保护成员的类,并通过一个公共接口对其进行修改,通常什么时候可以直接访问受保护成员?我想到了一些具体的例子:
我不想公开这些属性,因为我不想公开地触摸它们。我的语法IDE语法高亮显示,我在访问受保护的成员时错了-谁在这里?
编辑 -在下面添加一个简单的示例:
class Complex:
def __init__(self, imaginary, base):
self._imaginary = imaginary
self._base = base
def __str__(self):
return "%fi + %f" % self._base, self._imaginary
def __add__(self, other):
return Complex(self._imaginary + other._imaginary, self._base + other._base)
Run Code Online (Sandbox Code Playgroud)
Pycharm 使用以下内容突出显示other._imaginary和other._base:
访问类的受保护成员_imaginary
我有一个 ABC 方法,子类应该返回他们自己的类型,我正在尝试找出最好的方法来提示这个。例如:
from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def f(self): ## here i want a type hint for type(self)
pass
class Blah(Base):
def __init__(self, x: int):
self.x = x
def f(self) -> "Blah":
return Blah(self.x + 1)
Run Code Online (Sandbox Code Playgroud)
我能想到的最好的是这个,它有点沉重:
from abc import ABC, abstractmethod
from typing import TypeVar, Generic
SELF = TypeVar["SELF"]
class Base(ABC, Generic[SELF]):
@abstractmethod
def f(self) -> SELF:
pass
class Blah(Base["Blah"]):
def __init__(self, x: int):
self.x = x
def f(self) -> "Blah":
return Blah(self.x+1)
Run Code Online (Sandbox Code Playgroud)
我有更好/更清洁的方法吗?
from dataclasses import dataclass
@dataclass
class InventoryItem:
"""Class for keeping track of an item in inventory."""
name: str | None = None
unit_price: float
quantity_on_hand: int = 0
Run Code Online (Sandbox Code Playgroud)
类型错误: | 不支持的操作数类型:“type”和“NoneType”
Python 3.9
我认为问题是使用最新版本的python,如何解决。
我尝试使用“或”,但没有帮助
python ×10
python-3.x ×4
type-hinting ×4
annotations ×2
types ×2
typing ×2
abc ×1
attributes ×1
class ×1
nonetype ×1
oop ×1
protected ×1
python-3.5 ×1
recursion ×1
typechecking ×1