如何创建仅在满足某些条件时才进行实例化的类?

时间:2019-06-16 11:15:37

标签: python python-3.x class oop instance

让我说我上了这个课:

class Person:
    def __init__(self, name):
        self.name = name

如果我要实例化Person,我可以这样做:

me = Person("António")

但是如果Person的类型为name时我只想实例化str怎么办?
我尝试过:

class Person:
    def __init__(self, name):
        if type(name) == str:
            self.name = name

但是当我这样做时:

me = Person("António")
print(me.name)

you = Person(1)
print(you.name)

我明白了:

enter image description here

所有发生的事情是:

  • 如果namestr,则实例具有.name方法
  • 如果name不是str,则实例没有.name方法

但是我真正想要的是,如果name不是str,则停止全部实例化。
换句话说,我希望不可能通过Person类创建一个非str name对象。

我该怎么做?

4 个答案:

答案 0 :(得分:1)

您可以使用检查参数的工厂,并在一切正常的情况下返回Person对象,或者引发错误:

也许是这样:

class PersonNameError(Exception):
    pass

class Person:
    def __init__(self):
        self.name = None

def person_from_name(name: str) -> Person:
    """Person factory that checks if the parameter name is valid
    returns a Person object if it is, or raises an error without 
    creating an instance of Person if not.
    """
    if isinstance(name, str):
        p = Person()
        p.name = name
        return p
    raise PersonNameError('a name must be a string')

p = person_from_name('Antonio') 

位置:

p = person_from_name(123)   # <-- parameter name is not a string

引发异常:

PersonNameError                           Traceback (most recent call last)
<ipython-input-41-a23e22774881> in <module>
     14 
     15 p = person_from_name('Antonio')
---> 16 p = person_from_name(123)

<ipython-input-41-a23e22774881> in person_from_name(name)
     11         p.name = name
     12         return p
---> 13     raise PersonNameError('a name must be a string')
     14 
     15 p = person_from_name('Antonio')

PersonNameError: a name must be a string

答案 1 :(得分:0)

怎么样:

set.seed(16)
x.test<-data.frame(runif(100,0,2))
eps.test<-rnorm(100,sd=0.1)
y.test<-sin(x.test)+eps.test
linear_prediction<-predict(model, x.test, interval="prediction")

答案 2 :(得分:0)

您应该使用factory design pattern。您可以详细了解here。简单来说:

创建将检查条件的类/方法,并仅在满足这些条件时才返回新的类实例。

答案 3 :(得分:0)

如果你想修改实例化行为, 您可以创建一个构造函数, 使用类方法。

class Person:
    def __init__(self, name):
        self.name = name
        print("ok")

    @classmethod
    def create(cls, name):
        if not isinstance(name, str):
            raise ValueError(f"Expected name to be a string, got {type(name)}")
        return cls(name)
           
me = Person.create("António")
print(me.name)

you = Person.create(1)
print(you.name)

OK 打印一次,只证明一次实例化

ok
António
Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 17, in <module>
  File "<string>", line 11, in create
ValueError: Expected name to be a string, got <class 'int'>

[Program finished]

这里,这是一个正在完成的显式测试。 很少需要覆盖 new 并且对于日常正常课程,我认为应该避免它。这样做可以使类实现变得简单。

class Test(object):
     print("ok")
     def __new__(cls, x):
         if isinstance(x, str) :           
             print(x)
         else:
             raise ValueError(f"Expected name to be a string, got {type(x)}")
 
obj1 = Test("António")

obj2 = Test(1)
ok
António
Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 14, in <module>
  File "<string>", line 10, in __new__
ValueError: Expected name to be a string, got <class 'int'>

[Program finished]