【问题标题】:python 2.7 How to make function that is used by super and sub class with their own attributes w/o an attribute error?python 2.7 如何使超类和子类使用的函数具有自己的属性而没有属性错误?
【发布时间】:2025-03-30 00:10:01
【问题描述】:

我可能可以使用 try except 函数,但是我很想知道是否有更好的方法来做到这一点。这是函数。

class Superswag():
  def __init__(self, name, where):
    self.name = name
    self.where = where
class Real(Superswag):        
  def __init__(self, name, amt_of_buckles):
    self.name = name
    self.amt_of_buckles = 0


hat = Superswag("hat","head")
jacket = Real("Jacket",10)
def isitcool(object):
    if object.name == "coat":
            return True
    elif object.amt_of_buckles >= 5:
            return True
    else:
            return False


isitcool(hat)
isitcool(jacket)



File "XXXXXXXX", line 16, in isitcool
elif object.amt_of_buckles >= 5:
AttributeError: 'Superswag' object has no attribute 'amt_of_buckles'

【问题讨论】:

    标签: python-2.7 function class oop subclass


    【解决方案1】:

    Nvm,找到isinstance函数。

    elif isinstance(object,Real) and object.amt_of_buckles >= 5:
    

    【讨论】:

      最近更新 更多