python 实例化_防止类在Python中直接实例化

1586010002-jmsa.png

I have a super class with a method that calls other methods that are only defined in its sub classes. That's why, when I create an instance of my super class and call its method, it cannot find the method and raises an error.

Here is an example:

class SuperClass(object):

def method_one(self):

value = self.subclass_method()

print value

class SubClassOne(SuperClass):

def subclass_method(self):

return 'subclass 1'

class SubClassTwo(SuperClass):

def subclass_method(self):

return 'nubclass 2'

s1 = SubClassOne()

s1.method_one()

s2 = SubClassTwo()

s2.method_one()

c = SuperClass()

c.method_one()

# Results:

# subclass 1

# nubclass 2

# Traceback (most recent call last):

# File "abst.py", line 28, in

# c.method_one()

# File "abst.py", line 4, in method_one

# value = self.subclass_method()

# AttributeError: 'SuperClass' object has no attribute 'subclass_method'

I was thinking about changing the init of super class and verify the type of object, when a new instance is created. If the object belongs to super class raise an error. However, I'm not too sure if it's the Pythonic way of doing it.

Any recommendations?

解决方案

You're talking about Abstract Base Classes, and the Python language does not support them natively.

However, in the standard library, there is a module you can use to help you along. Check out the abc documentation.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值