CodeQL documentation

Superclass attribute shadows subclass method

ID: py/attribute-shadows-method
Kind: problem
Security severity: 
Severity: error
Precision: high
Tags:
   - quality
   - reliability
   - correctness
Query suites:
   - python-security-and-quality.qls

Click to see the query in the CodeQL repository

Subclass shadowing occurs when an instance attribute of a superclass has the the same name as a method of a subclass, or vice-versa. The semantics of Python attribute look-up mean that the instance attribute of the superclass hides the method in the subclass.

Recommendation

Rename the method in the subclass or rename the attribute in the superclass.

Example

The following code includes an example of subclass shadowing. When you call Cow().milk() an error is raised because Cow().milk is interpreted as the ‘milk’ attribute set in Mammal.__init__, not the ‘milk’ method defined within Cow. This can be fixed by changing the name of either the ‘milk’ attribute or the ‘milk’ method.

class Mammal(object):

    def __init__(self, milk = 0):
        self.milk = milk


class Cow(Mammal):

    def __init__(self):
        Mammal.__init__(self)

    def milk(self):
        return "Milk"

#Cow().milk() will raise an error as Cow().milk is the 'milk' attribute
#set in Mammal.__init__, not the 'milk' method defined on Cow.

  • © GitHub, Inc.
  • Terms
  • Privacy
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy