vedant mehta
vedant mehta

Reputation: 13

Assign an additional class to a variable in python (equivalence in R shown)

In R, you can do something like this:

x <- 3
cl <- class(x)
class(x) <- c("abc",cl)

So variable 'x' will be an integer as well as belong to user-defined class 'abc'.

I want to do a similar thing in Python. My variable 'x' should be considered as integer and should also have the attributes of user-defined class named "abc".

Upvotes: 1

Views: 44

Answers (1)

cdlane
cdlane

Reputation: 41905

Yes, Python supports multiple inheritance:

class indigestion():
    def burp(self):
        return " ".join("burp" for _ in range(int(self)))


class int_with_indigestion(int, indigestion):
    pass

class float_with_indigestion(float, indigestion):
    pass

n = int_with_indigestion(13)

print(n ** 2)
print(n.burp())

f = float_with_indigestion(5.3)

print(f ** 2)
print(f.burp())

USAGE

> python3 test.py
169
burp burp burp burp burp burp burp burp burp burp burp burp burp
28.09
burp burp burp burp burp
>

Upvotes: 2

Related Questions