Topher
Topher

Reputation: 498

Python: typecasting a variable in an object method declaration?

I'm new to Python, and have a class such as the following:

class myclass:
    var1 = 0
    var2 = 1
    var3 = 2
    def function(self, x):
        x.method(...yadda...)

For this class, x is another object containing data and some methods, and I'd like to be able to call those methods from within an instance of myclass. Is there a way to specify x here as an object of another type? For instance, regularly one would use the following to define an object (from an imported file called classfile):

newObj = classfile.myClass()

For the object x in the code above, can I require it be of a specific object type, be it a built-in object or one I define? How would you specify this?

I would want the code to throw an error or bypass any object sent in that is not of the desired type, preferably before I start attempting to call methods in it (i.e. x.method()).

Upvotes: 0

Views: 173

Answers (1)

John
John

Reputation: 13709

A better practice would be to "implement" duck typing. So in your case

def function(self, x):
    try:
        x.method(... yada ...)
    except AttributeError:
        raise MyAPIError

Upvotes: 2

Related Questions